-3

我的代码只能返回响应状态消息或状态代码,但我需要我的代码以“查看源”格式返回响应,即 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);
    }
}
4

1 回答 1

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());
    }
}
于 2013-04-11T11:24:21.880 回答