JavaでHTTPレスポンスヘッダを取得する方法

この例では、JavaでHttp応答ヘッダー値を取得する方法を示します。

{空} 1。標準のJDKの例

    URL obj = new URL("/");
    URLConnection conn = obj.openConnection();

   //get all headers
    Map<String, List<String>> map = conn.getHeaderFields();
    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() +
                 " ,Value : " + entry.getValue());
    }

   //get header by 'key'
    String server = conn.getHeaderField("Server");

{空} 2。 Apache HttpClientの例

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("/");
    HttpResponse response = client.execute(request);

   //get all headers
    Header[]headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName()
              + " ,Value : " + header.getValue());
    }

   //get header by 'key'
    String server = response.getFirstHeader("Server").getValue();

1. URLConnectionの例

URLConnectionを使用してレスポンスヘッダーの値を取得する方法の完全な例を参照してください。

ResponseHeaderUtil.java

package com.mkyong;

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

public class ResponseHeaderUtil {

  public static void main(String[]args) {

    try {

    URL obj = new URL("/");
    URLConnection conn = obj.openConnection();
    Map<String, List<String>> map = conn.getHeaderFields();

    System.out.println("Printing Response Header...\n");

    for (Map.Entry<String, List<String>> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey()
                           + " ,Value : " + entry.getValue());
    }

    System.out.println("\nGet Response Header By Key ...\n");
    String server = conn.getHeaderField("Server");

    if (server == null) {
        System.out.println("Key 'Server' is not found!");
    } else {
        System.out.println("Server - " + server);
    }

    System.out.println("\n Done");

    } catch (Exception e) {
    e.printStackTrace();
    }

  }
}

出力

Printing Response Header...

Key : null ,Value :[HTTP/1.1 200 OK]Key : ETag ,Value :["713cd-9b82-4dd6d789447c0"]Key : Content-Length ,Value :[39810]Key : Expires ,Value :[Fri, 24 May 2013 03:22:31 GMT]Key : Last-Modified ,Value :[Fri, 24 May 2013 02:22:31 GMT]Key : Connection ,Value :[Keep-Alive]Key : X-Powered-By ,Value :[W3 Total Cache/0.9.2.9]Key : Server ,Value :[Apache/2.2.22 (Unix) mod__ssl/2.2.22 OpenSSL/1.0.0-fips mod__auth__passthrough/2.1 mod__bwlimited/1.4 FrontPage/5.0.2.2635]Key : Pragma ,Value :[public]Key : Cache-Control ,Value :[public]Key : Date ,Value :[Fri, 24 May 2013 02:22:37 GMT]Key : Vary ,Value :[Accept-Encoding,Cookie]Key : Keep-Alive ,Value :[timeout=2, max=100]Key : Content-Type ,Value :[text/html]Key : Accept-Ranges ,Value :[bytes]
Get Response Header By Key ...

Server - Apache/2.2.22 (Unix) mod__ssl/2.2.22 OpenSSL/1.0.0-fips mod__auth__passthrough/2.1 mod__bwlimited/1.4 FrontPage/5.0.2.2635

Done

2. Apache HttpClientの例

これは同等の例ですが、Apache HttpClientを使用しています。

ResponseHeaderUtil.java

package com.mkyong;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

public class ResponseHeaderUtil {

  public static void main(String[]args) {

    try {

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("/");
    HttpResponse response = client.execute(request);

    System.out.println("Printing Response Header...\n");

    Header[]headers = response.getAllHeaders();
    for (Header header : headers) {
        System.out.println("Key : " + header.getName()
                           + " ,Value : " + header.getValue());

    }

    System.out.println("\nGet Response Header By Key ...\n");
    String server = response.getFirstHeader("Server").getValue();

    if (server == null) {
        System.out.println("Key 'Server' is not found!");
    } else {
        System.out.println("Server - " + server);
    }

    System.out.println("\n Done");

    } catch (Exception e) {
    e.printStackTrace();
    }
  }
}

参考文献

  1. http://ja.wikipedia.org/wiki/List of HTTP header fields[Wiki:リスト

HTTPヘッダーフィールド]。 link://java/how-to-get-http-request-header-in-java/[HTTPを取得する方法

Javaで要求ヘッダー]。 http://docs.oracle.com/javase/6/docs/api/java/net/URLConnection.html#getHeaderFields() [URLConnection.html#getHeaderFields()

Java Doc]。リンク:hc.apache.org/[Apache Http Components - HttpClient]

  1. link://java/how-to-send-http-request-getpost-in-java/[HTTPを送信する方法

JavaでGET/POSTを要求]

ヘッダー リンク://タグ/httpclient/[httpclient] レスポンスヘッダー

次の投稿:Java - 文字配列を文字列に変換する方法