我正在使用 Apache HttpClient 获取页面,我想将服务器回复的 http 正文存储到一个字符串中,以便我可以操作该字符串并将其打印到控制台。
不幸的是,当运行此方法时,我收到此消息:
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 类:
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;
}
您正在呼叫toString
on the InputStream
当它已经读完之后。您需要从字节数组创建字符串。获取内容的字符串版本的更简单方法是使用EntityUtils.toString(HttpEntity) http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/util/EntityUtils.html#toString%28org.apache.http.HttpEntity%29
确切的实现如下所示:
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)