JAVA获取HTTP请求头的方法示例

本文实例讲述了JAVA获取HTTP请求头的方法。分享给大家供大家参考,具体如下:

在利用Java网络编程时,利用Java获取HTTP Request 和 Response头字段;

可以利用Java语言根据需要添加自定义的HTTP头字段,而不必拘泥于标准HTTP定义的头字段。

代码如下:

public class TestURL {
  public static void main(String[] args) {
    String destURLStr= "http://www.baidu.com";
    URL destURL = null;
    URLConnection urlCon = null;
    HttpURLConnection httpUrlCon= null;
    String readResFile = "C:/Users/zhoujw/Desktop/readResFile.html";
    BufferedWriter bw = null;
    try {
      bw = new BufferedWriter(new FileWriter(readResFile));
      destURL = new URL(destURLStr);
      urlCon = destURL.openConnection();
      httpUrlCon = (HttpURLConnection)urlCon;
      //set request property
      httpUrlCon.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
      //可根据需要添加自定义请求头
      httpUrlCon.setRequestProperty("Test Header1", "test1");
      httpUrlCon.setRequestProperty("Test Header2", "test2");
      httpUrlCon.connect();
      BufferedReader br = new BufferedReader(new InputStreamReader(httpUrlCon.getInputStream(), "gbk"));
      String webpage = null;
      while((( webpage = br.readLine()) != null))
      {
//       System.out.println(webpage);
        bw.write(webpage);
        bw.flush();
      }
      //debug
      System.out.println("Self Define Headers:");
      System.out.println(" Test Header1: " + httpUrlCon.getRequestProperty("Test Header1"));
      System.out.println(" Test Header2: " + httpUrlCon.getRequestProperty("Test Header2"));
      System.out.println();
      //echo request property
      echoRequestHeaders(httpUrlCon);
      //echo response property
      echoResponseHeaders(httpUrlCon);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static void echoRequestHeaders(HttpURLConnection httpUrlCon){
    System.out.println("Request Headers:");
    System.out.println(" " + httpUrlCon.getRequestMethod() + " / " + " HTTP/1.1");
    System.out.println(" Host: " + httpUrlCon.getRequestProperty("Host"));
    System.out.println(" Connection: " + httpUrlCon.getRequestProperty("Connection"));
    System.out.println(" Accept: " + httpUrlCon.getRequestProperty("Accept"));
    System.out.println(" User-Agent: " + httpUrlCon.getRequestProperty("User-Agent"));
    System.out.println(" Accept-Encoding: " + httpUrlCon.getRequestProperty("Accept-Encoding"));
    System.out.println(" Accept-Language: " + httpUrlCon.getRequestProperty("Accept-Language"));
    System.out.println(" Cookie: " + httpUrlCon.getRequestProperty("Cookie"));
    System.out.println(" Connection: " + httpUrlCon.getHeaderField("Connection"));//利用另一种读取HTTP头字段
    System.out.println();
  }
  public static void echoResponseHeaders(HttpURLConnection httpUrlCon) throws IOException{
    System.out.println("Response Headers:");
    System.out.println(" " + "HTTP/1.1 " + httpUrlCon.getResponseCode() + " " + httpUrlCon.getResponseMessage());
    System.out.println(" status: " + httpUrlCon.getResponseCode() + " " + httpUrlCon.getResponseMessage());
    System.out.println(" content-encoding: " + httpUrlCon.getContentEncoding());
    System.out.println(" content-length : " + httpUrlCon.getContentLength());
    System.out.println(" content-type: " + httpUrlCon.getContentType());
    System.out.println(" Date: " + httpUrlCon.getDate());
    System.out.println(" ConnectTimeout: " + httpUrlCon.getConnectTimeout());
    System.out.println(" expires: " + httpUrlCon.getExpiration());
    System.out.println(" content-type: " + httpUrlCon.getHeaderField("content-type"));//利用另一种读取HTTP头字段
    System.out.println();
  }
}

运行结果:

Self Define Headers:
 Test Header1: test1
 Test Header2: test2
Request Headers:
 GET / HTTP/1.1
 Host: www.baidu.com
 Connection: keep-alive
 Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
 User-Agent: Java/1.6.0_20
 Accept-Encoding: gzip,deflate,sdch
 Accept-Language: null
 Cookie: null
 Connection: Keep-Alive
http://www.baidu.com
Response Headers:
 HTTP/1.1 200 OK
 status: 200 OK
 content-encoding: gzip
 content-length : -1
 content-type: text/html; charset=utf-8
 Date: 1427817028000
 ConnectTimeout: 0
 expires: 1427817001000
 content-type: text/html; charset=utf-8

更多关于java相关内容感兴趣的读者可查看本站专题:《Java Socket编程技巧总结》、《Java文件与目录操作技巧汇总》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

(0)

相关推荐

  • java获取http请求的Header和Body的简单方法

    在http请求中,有Header和Body之分,读取header使用request.getHeader("..."); 读取Body使用request.getReader(),但getReader获取的是BufferedReader,需要把它转换成字符串,下面是转换的方法. public class TestController { @RequestMapping("/a") protected void doPost(HttpServletRequest requ

  • java发送http的get、post请求实现代码

    Http请求类 package wzh.Http; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.URL; import java.net.URLConnection; import java.util.List; import java.util.Map; public

  • java模拟http的Get/Post请求,并设置ip与port代理的方法

    本文涉及3个基本点: 1.因为很多公司的内网都设有代理,浏览器通过ip与port上网,而java代码模拟http get方式同样需要外网代理: 2.Java实现http的Get/Post请求代码: 3.主要是设置HttpURLConnection请求头里面的属性 比如Cookie.User-Agent(浏览器类型)等等. 比如:http请求中添加Header conn.setRequestProperty("Authorization", authorization); 注:我就在网上

  • java实现http请求工具类示例

    通过http rest请求返回数据 复制代码 代码如下: import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.http.NameValuePair;import org.apache.http.client.ClientProtocolException;import org.apache.http.client.HttpClient;import

  • java遍历http请求request的所有参数实现方法

    通过程序遍历http请求的所有参数放到hashmap中,用的时候方便了. 如果参数值有中文,那么需要在程序中添加filter转码,或者在下面程序里,对paramValue转码 如下所示: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Map map = new HashMap(); Enumeration para

  • java实现http的Post、Get、代理访问请求

    本文实例讲解了java实现http的Post.Get.代理访问请求的详细代码片段,分享给大家供大家参考,具体内容如下 package com.snowfigure.kits.net; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; im

  • Java 发送http请求上传文件功能实例

    废话不多说了,直接给大家贴代码了,具体代码如下所示: package wxapi.WxHelper; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputSt

  • java使用httpclient模拟post请求和get请求示例

    复制代码 代码如下: import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader; import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;import org.apache.commons.httpclient.Header;import org

  • JAVA发送HTTP请求,返回HTTP响应内容,应用及实例代码

    JDK 中提供了一些对无状态协议请求(HTTP )的支持,下面我就将我所写的一个小例子(组件)进行描述:首先让我们先构建一个请求类(HttpRequester ).该类封装了 JAVA 实现简单请求的代码,如下: 复制代码 代码如下: import java.io.BufferedReader;  import java.io.IOException;  import java.io.InputStream;  import java.io.InputStreamReader;  import

  • java发送http请求并获取状态码的简单实例

    目前做项目中有一个需求是这样的,需要通过java发送url请求,查看该url是否有效,这时我们可以通过获取状态码来判断. try { URL u = new URL("http://10.1.2.8:8080/fqz/page/qizha/pros_add.jsp"); try { HttpURLConnection uConnection = (HttpURLConnection) u.openConnection(); try { uConnection.connect(); Sy

  • java发送http get请求的两种方法(总结)

    长话短说,废话不说 一.第一种方式,通过HttpClient方式,代码如下: public static String httpGet(String url, String charset) throws HttpException, IOException { String json = null; HttpGet httpGet = new HttpGet(); // 设置参数 try { httpGet.setURI(new URI(url)); } catch (URISyntaxExc

  • java读取http请求中的body实例代码

    在http请求中,有Header和Body之分,读取header使用request.getHeader("..."); 读取Body使用request.getReader(),但getReader获取的是BufferedReader,需要把它转换成字符串, 下面是转换的方法. public static String getBodyString(BufferedReader br) { String inputLine; String str = ""; try {

随机推荐