我想查看Java中HTTP请求生成的响应的“源代码”

时间:2013-04-11 11:17:27

标签: java

我的代码只能返回响应状态消息或状态代码,但我需要我的代码以“查看源”格式返回响应,即XML格式:

import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;

public class API{
    public static void main(String args[]) throws IOException
    {
        URL url = new URL("http://example.com");
        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        String statusCode = http.getResponseMessage();
        System.out.println(statusCode);
    }
}

1 个答案:

答案 0 :(得分:0)

你必须得到流然后阅读它。像这样:

import java.io.IOException;
import java.net.URL;
import java.net.HttpURLConnection;

public class API{
    public static void main(String args[]) throws IOException
    {
        URL url = new URL("http://example.com");

        HttpURLConnection http = (HttpURLConnection)url.openConnection();
        String statusCode = http.getResponseMessage();
        System.out.println(statusCode);

          //read the result from the server
          BufferedReader rd  = new BufferedReader(new InputStreamReader(http.getInputStream()));
          StringBuilder sb = new StringBuilder();
          String line = null;
          while ((line = rd.readLine()) != null)
          {
              sb.append(line);
          }

          System.out.println(sb.toString());
    }
}