Java中的Apache HttpClient instream.toString = org.apache.http.conn.EofSensorInputStream [英] Apache HttpClient in Java, instream.toString = org.apache.http.conn.EofSensorInputStream
问题描述
我正在使用Apache HttpClient获取页面,并且要将服务器答复的http正文存储为字符串,以便随后可以操纵此字符串并将其打印到控制台.
I am GETting a page with Apache HttpClient and I want to store the server reply's http body into a string so I can then manipulate this string and print it to the console.
不幸的是,当运行此方法时,我会收到此消息:
Unfortunately when running this method I get this message back:
17:52:01,862 INFO Driver:53 - fetchPage STARTING
17:52:07,580 INFO Driver:73 - fetchPage ENDING, took 5716
org.apache.http.conn.EofSensorInputStream@5e0eb724
fetchPage类:
The fetchPage Class:
public String fetchPage(String part){
log.info("fetchPage STARTING");
long start = System.currentTimeMillis();
String reply;
String searchurl = URL + URL_SEARCH_BASE + part + URL_SEARCH_TAIL;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(searchurl);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
int l;
byte[] tmp = new byte[2048];
while ((l = instream.read(tmp)) != -1) {
}
long elapsedTimeMillis = System.currentTimeMillis()-start;
log.info("fetchPage ENDING, took " + elapsedTimeMillis);
reply = instream.toString();
System.out.println(reply);
return reply;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
推荐答案
您已经在InputStream
上读通了toString
.您需要从字节数组创建字符串.获取内容的字符串版本的更简单方法是使用
You are calling the toString
on the InputStream
after it has already read through. You need to create your string from the byte arrays. The simpler way to get the String version of the content is to use the EntityUtils.toString(HttpEntity)
确切的实现如下:
import org.apache.http.util.EntityUtils;
public String fetchPage(String part){
log.info("fetchPage STARTING");
long start = System.currentTimeMillis();
String reply;
String searchurl = URL + URL_SEARCH_BASE + part + URL_SEARCH_TAIL;
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(searchurl);
HttpResponse response;
try {
response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
这篇关于Java中的Apache HttpClient instream.toString = org.apache.http.conn.EofSensorInputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!