如何使用HttpClient
我目前正在尝试使用 java 中的以下代码通过“uri”获取一些数据:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream stream = entity.getContent();
callString = stream.toString();
return callString;
}
但这不起作用。有谁知道我在这里做错了什么?
I'm currently trying to get some data via a 'uri' using the following code in java:
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(uri);
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
if(entity != null){
InputStream stream = entity.getContent();
callString = stream.toString();
return callString;
}
However this isn't working. Does anyone know what I'm doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您不能像那样打印出输入流...相反,请执行以下操作:-
打印输出如下所示:-
You cannot print out the input stream like that... instead, do something like this:-
The printout looks like this:-
这完全是猜测,但不应该是:
Its a total guess but shouldn't it be:
您正在尝试下载文件,并且 getEntity 用于获取您指定类型的对象。恕我直言,这行不通。
您需要编写能够实际读取响应流并从中读取内容的代码...
您想做什么?
you are trying to download a file and getEntity is used get an object for a type you have specified. IMHO this wont work.
You need to code which will actually read the response stream and read contents out of it...
What are you trying to do ?
要将生成的实体读取为字符串,请使用
EntityUtils.toString(HttpEntity)
或EntityUtils.toString(HttpEntity, String)
如果您知道字符集。To read the resulting entity to a String use
EntityUtils.toString(HttpEntity)
orEntityUtils.toString(HttpEntity, String)
if you know the character set.如果您收到 NetworkOnMainThreadException 那么这意味着您正在调用 client.execute(get);在主线程上,这是在 Honeycomb 及更高版本上抛出的异常。请参阅http://developer.android.com/reference/android/os/NetworkOnMainThreadException。 html 了解详细信息。解决方案是在新线程中运行它。
If you are getting NetworkOnMainThreadException then that means you are calling client.execute(get); on the main thread which is an exception thrown on Honeycomb and higher. See http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html for details. The solution is to run this in a new thread.