HttpURLConnection:getResponseMessage(),getInputStream()和getContent()

时间:2015-12-17 11:03:00

标签: java httpurlconnection

我遇到过如下代码,

private static String getResponse (HttpURLConnection connection) throws Exception
{
   String responseString = null;
   int responseCode = connection.getResponseCode();
   String responseMessage = connection.getResponseMessage();
   Log.debug("%s - Response code is \"%s\" with message \"%s\"",
          methodName, responseCode, responseMessage);
   String line = null;
   if (responseCode == HttpURLConnection.HTTP_OK) {
       BufferedReader bufferedReader = null;
       try {
           InputStream inputStream = connection.getInputStream();
           if (inputStream != null) {
               bufferedReader = Util.bufferedReader(
                   inputStream, Util.Encod.UTF8);
               StringBuilder response = new StringBuilder();
               while ((line = bufferedReader.readLine()) != null) {
                   response.append(line);
                   response.append(Util.getNewLine());
               }
               responseString = response.toString();
           }
       }
       finally {
           if (bufferedReader != null) {
               bufferedReader.close();
           }
       }
       Log.signature.debug(
           "%s - Received following JSON response : %s",
           methodName,
           responseString);
   }
   return responseString;
} 

他们已经收到了如下所示的回复吗?

String responseMessage = connection.getResponseMessage()

然后他们为什么再次使用connection.getInputStream()

有什么不同吗?

如果可能,请您解释一些示例或何时使用以下内容getResponseMessage() / getInputStream()

Class URLConnection 
   public Object getContent() throws IOException 
   public Object getContent(Class[] classes) throws IOException

1 个答案:

答案 0 :(得分:1)

getResponseMessage()用于获取连接的消息,例如 HTTP_NOT_FOUND

HTTP Status-Code 404: Not Found.

要获取getInputStream()所需的实际数据,请参阅以下详细信息:

public InputStream getInputStream() throws IOException

返回从此打开的连接读取的输入流。 如果读取超时在数据可用于读取之前到期,则从返回的输入流中读取时可以抛出SocketTimeoutException

  

返回:   从此打开的连接读取的输入流。

     

抛出:   IOException - 如果在创建输入流时发生I / O错误。   UnknownServiceException - 如果协议不支持输入。

请参阅以下链接了解更多详情: http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getInputStream()