2013-04-11 86 views
-3

我的代码只能返回响应状态消息或状态代码,但我需要我的代码以“查看源代码”格式返回响应,即以XML格式:我想查看Java代码中HTTP请求产生的响应的“源代码”

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); 
    } 
} 
+0

似乎是真正的问题?为什么负面投票? – 2013-04-11 11:19:41

+0

也许因为你可以通过在谷歌的“HttpURLConnection示例”中输入来获得答案。 – Mateusz 2013-04-11 11:28:28

+0

可能重复的[如何从HTTP请求生成完整的响应代码在Java?](http://stackoverflow.com/questions/15946612/how-to-generate-entire-response-code-from-http-request-in -java) – Qwerky 2013-04-11 11:39:43

回答

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()); 
    } 
} 
+0

尝试了这段代码,但它在行“sb.append(line +'\ n');”说operator +是未定义的。 – 2013-04-11 11:57:17

+0

现在尝试,但没关系,你可以把它扔掉'“+'\'\ n'”' – Mateusz 2013-04-11 12:17:02

+0

谢谢。那么说..OMG – 2013-04-12 11:56:01