【发布时间】:2013-09-14 15:12:37
【问题描述】:
为什么下面的代码返回-1?好像请求失败了。
public static void main(String[] args)
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://www.google.de");
HttpResponse response;
try
{
response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
// Prints -1
System.out.println(entity.getContentLength());
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
httpGet.releaseConnection();
}
}
是否可以将响应作为字符串获取?
【问题讨论】:
-
getContentLength的 Javadoc:内容的字节数,如果未知,则为负数。 -
有据可查...有什么解决这个问题的建议吗?
-
为什么需要以内容长度开头?使用响应内容(可能是
InputStream)而不是通过这种机制验证响应会更好。 -
是否可以将响应作为字符串获取? 是的。尝试一些事情,而不是询问codez。
标签: java http apache-httpcomponents