返回顶部

收藏

java发起http请求获得相应头代码

更多
package cn.outofmemory.snippets.core;

import java.net.URL;
import java.net.URLConnection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GetResponseHeadersFromHTTPRequest {

    public static void main(String[] args) throws Exception {

        URL url = new URL("http://www.google.com:80");
        URLConnection conn = url.openConnection();

        Map<String, List<String>> headerFields = conn.getHeaderFields();

        Set<String> headerFieldsSet = headerFields.keySet();
        Iterator<String> hearerFieldsIter = headerFieldsSet.iterator();

        while (hearerFieldsIter.hasNext()) {

             String headerFieldKey = hearerFieldsIter.next();
             List<String> headerFieldValue = headerFields.get(headerFieldKey);

             StringBuilder sb = new StringBuilder();
             for (String value : headerFieldValue) {
                 sb.append(value);
                 sb.append("");
            }

             System.out.println(headerFieldKey + "=" + sb.toString());

        }

    }

}

http响应头输出:

null=HTTP/1.1 200 OK
X-Frame-Options=SAMEORIGIN
Date=Sat, 29 Oct 2011 19:59:40 GMT
Transfer-Encoding=chunked
Expires=-1
X-XSS-Protection=1; mode=block
Set-Cookie=NID=52=k77gRcAV5E3Gh7PIobW26tSHsyc2gBeTEOHastZBxQdvqJ5JwfFCbhEaJh8uQ0bH3PFNvnpeGGtumB8pe1XWMcF7dQC9TugHOgzseBEl6CxOTmcvq_RHGwdQcFq6LUZQ; expires=Sun, 29-Apr-2012 19:59:40 GMT; path=/; domain=.google.gr; HttpOnlyPREF=ID=a372139a705e35a1:FF=0:TM=1319918380:LM=1319918380:S=i8JHod81lVWzINZg; expires=Mon, 28-Oct-2013 19:59:40 GMT; path=/; domain=.google.gr
Content-Type=text/html; charset=ISO-8859-7
Server=gws
Cache-Control=private, max-age=0

标签:java,http,基础

收藏

0人收藏

支持

0

反对

0

发表评论