gpt4 book ai didi

java - Java 中的 Apache HttpClient,instream.toString = org.apache.http.conn.EofSensorInputStream

转载 作者:搜寻专家 更新时间:2023-10-31 19:30:50 25 4
gpt4 key购买 nike

我正在使用 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;
}

最佳答案

您在 InputStream 读取完后调用 toString。您需要从字节数组创建字符串。获取内容的字符串版本的更简单方法是使用 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 - Java 中的 Apache HttpClient,instream.toString = org.apache.http.conn.EofSensorInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6217011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com