0

我正在使用Apache 库中的HttpEntity从 URL 下载文件。IE

String url="http://www.stackoverflow.com/question/ask/idontexist.jpg";
String user_agent=...; //I know, I can use the default value, but this is what I do actually!


HttpClient httpclient =new AutoRetryHttpClient(new DefaultServiceUnavailableRetryStrategy(5, 500));

HttpGet httpget = new HttpGet(url);
httpget.setHeader("Content-Type", "application/x-www-form-urlencoded");
httpget.setHeader("User-Agent", user_agent);

HttpEntity entity = httpclient.execute(httpget).getEntity(); 

InputStream is = entity.getContent();

现在。如果我InputStream通过 a保存资源,FileOutputStream我会得到一个名为 的文件idontexist.jpg,但它没有内容(如预期的那样)。

如何验证返回InputStream的内容没有内容或 URL 指向的请求资源不存在?

4

1 回答 1

2

You should first get HttpResponse object with

HttpResponse httpResponse = httpclient.execute(httpget);

Then you can get status code with

int statusCode = httpResponse.getStatusLine().getStatusCode();

and, if the resource is found, get http entity with

HttpEntity entity = httpResponse.getEntity();

Hope this helps,

Regards.

于 2013-06-04T09:41:03.827 回答