java-使用java.net检索网页 - 如何正确检索响应标头

时间:2012-01-10 21:26:39

标签: java google-app-engine

我正在尝试使用java.net连接到Google App Engine for Java中的远程URL。

连接后我想获取响应头---

我使用以下代码(连接并检索一些数据后) - 注 - 'client'表示HTTPUrlConnection对象。

//now get HTTP Response Headers...
for (Entry<String, List<String>> headernew : client.getHeaderFields().entrySet()) {
System.out.println(headernew.getKey() + "=" + headernew.getValue());
String currName = headernew.getKey();
String currValue = headernew.getValue();

现在,由于'headernew'被指定为值,因为List I不能设置'currValue',正如我在上面的代码中给出的那样。

首先使用'headernew'的代码行取自现有的SO答案。

上面的代码在哪里错了?我应该简单地将'headernew'设置如下 -

for (Entry<String, String> headernew : client.getHeaderFields().entrySet()) {

具体来说,我想检索以下数据 -

Mime类型,字符集,响应头作为键值对,以及响应体(声明为'byte []')

1 个答案:

答案 0 :(得分:1)

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map.Entry;

public class Test {

  public static void run() throws Throwable {

    HttpURLConnection client = null;
    OutputStreamWriter wr = null;
    BufferedReader rd = null;
    StringBuilder sb = null;
    String line = null;

    try {

      URL url = new URL("http://www.google.com");
      client = (HttpURLConnection) url.openConnection();
      client.setRequestMethod("GET");
      client.setDoOutput(true);
      client.setReadTimeout(10000);

      client.connect();
      System.out.println(" *** headers ***");
      for (Entry<String, List<String>> headernew : client.getHeaderFields().entrySet()) {
        System.out.println(headernew.getKey() + "=" + headernew.getValue());
      }

      System.out.println(" \n\n*** Body ***");
      rd = new BufferedReader(new InputStreamReader(client.getInputStream()));
      sb = new StringBuilder();

      while ((line = rd.readLine()) != null) {
        sb.append(line + '\n');
      }

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

    } finally {
      client.disconnect();
      rd = null;
      sb = null;
      wr = null;
    }
  }

  public static void main(String[] args) throws Throwable {
    run();
  }

}