首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >HttpURLConnection: getResponseMessage()、getInputStream()和getContent()之间的区别

HttpURLConnection: getResponseMessage()、getInputStream()和getContent()之间的区别
EN

Stack Overflow用户
提问于 2015-12-17 11:03:00
回答 1查看 2.8K关注 0票数 3

队员们,

我看到了下面的代码,

代码语言:javascript
运行
复制
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;
} 

在这里,他们已经收到了如下的答复,对吗?

代码语言:javascript
运行
复制
String responseMessage = connection.getResponseMessage()

那么他们为什么再次使用connection.getInputStream()呢?

有什么不同吗?

如果可能的话,请你也解释一些例子或什么时候使用比上面的getResponseMessage() / getInputStream()

代码语言:javascript
运行
复制
Class URLConnection 
   public Object getContent() throws IOException 
   public Object getContent(Class[] classes) throws IOException
EN

回答 1

Stack Overflow用户

发布于 2015-12-17 11:21:34

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

代码语言:javascript
运行
复制
HTTP Status-Code 404: Not Found.

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

代码语言:javascript
运行
复制
public InputStream getInputStream() throws IOException

返回从打开的连接读取的输入流。如果在数据可用之前读取超时,则从返回的输入流读取时可以引发SocketTimeoutException

返回:从打开的连接读取的输入流。 抛出: IOException -如果在创建输入流时发生I/O错误。UnknownServiceException -如果协议不支持输入。

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

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34332967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档