有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java HttpURLConnection:getResponseMessage()、getInputStream()和getContent()之间的差异

团队

我遇到了如下代码

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) 个答案

  1. # 1 楼答案

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

    HTTP Status-Code 404: Not Found.
    

    要通过getInputStream()获取实际数据,请查看以下详细信息:

    public InputStream getInputStream() throws IOException
    

    返回从该打开连接读取的输入流。 如果读取超时在数据可读取之前过期,则从返回的输入流读取时会抛出SocketTimeoutException

    Returns: an input stream that reads from this open connection.

    Throws: IOException - if an I/O error occurs while creating the input stream. UnknownServiceException - if the protocol does not support input.

    有关更多详细信息,请参阅以下链接: http://docs.oracle.com/javase/7/docs/api/java/net/URLConnection.html#getInputStream()