如何在Java中获取HTTP响应标题

时间:2020-02-23 14:34:19  来源:igfitidea点击:

在本教程中,我们将看到如何在Java中获取HTTP响应标题。
我们已经看到了如何在Java中发送或者发布请求。
我使用了相同的例子来演示获取HTTP响应标题。

package org.igi.theitroad.client;
 
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;
/**
 * @author igi Mandliya
*/
public class HttpURLConnectionExample {
 
 private final String USER_AGENT = "Mozilla/5.0";
 
 public static void main(String[] args) throws Exception {
 
  HttpURLConnectionExample http = new HttpURLConnectionExample();
 
  //Sending get request
  http.sendingGetRequest();
 }
 
 //HTTP GET request
 private void sendingGetRequest() throws Exception {
 
  String urlString = "https://www.theitroad.com";
 
  URL url = new URL(urlString);
  HttpURLConnection con = (HttpURLConnection) url.openConnection();
                //Get all header fields
  Map<String, List> map = con.getHeaderFields();
 
  System.out.println("Printing Response Header for URL: " + url.toString() + "n");
  for (Map.Entry> entry : map.entrySet()) {
   System.out.println(entry.getKey() + " : " + entry.getValue());
  }
 
  //get specific field
  String date = con.getHeaderField("Date");
  System.out.println("ngetting Date from response : " + date);
 
  //get specific field
  String server = con.getHeaderField("Server");
  System.out.println("ngetting Server from response : " + server);
 }
}

运行上面的代码时,我们将得到以下输出:

Printing Response Header for URL: http://www.theitroad.com
 
null : [HTTP/1.1 200 OK]
Transfer-Encoding : [chunked]
Vary : [Accept-Encoding]
Date : [Mon, 01 Aug 2015 17:58:23 GMT]
X-XSS-Protection : [1; mode=block]
Expires : [Mon, 01 Aug 2015 17:58:23 GMT]
Last-Modified : [Mon, 01 Aug 2015 17:49:36 GMT]
Accept-Ranges : [none]
Content-Type : [text/html; charset=UTF-8]
Server : [GSE]
X-Content-Type-Options : [nosniff]
Cache-Control : [private, max-age=0]
 
getting Date from response : Mon, 01 Aug 2015 17:58:23 GMT
 
getting Server from response : GSE