搜档网
当前位置:搜档网 › httpclient4抓取网页返回乱码

httpclient4抓取网页返回乱码

1、先看代码 。下面是一个通过Http协议以get方式去向指定的URL请求信息。

String pageUrl=“https://www.sodocs.net/doc/cc1382514.html,/”

String html = null;
HttpHost proxy = null;
proxy = new HttpHost(“10.221.41.192”,808 "http");

DefaultHttpClient httpClient = new DefaultHttpClient();// 创建httpClient对象
try {
URL url = new URL(pageUrl);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);//防止pageUrl中出现空格竖杠等特殊字符导致httpget请求失败
HttpGet httpget = new HttpGet(uri);// 以get体式格式请求该URL
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpResponse responce = httpClient.execute(httpget);// 获得responce对象
int resStatu = responce.getStatusLine().getStatusCode();// 返回码
if (resStatu == HttpStatus.SC_OK) {// 200正常 其它就代表错误
HttpEntity entity = responce.getEntity(); // 获得响应实体
if (entity != null) {
html = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset().toString());// 对返回的html代码进行解析
}
}
} catch (Exception e) {
log.error(e.toString());
} finally {
httpClient.getConnectionManager().shutdown();//关闭Http连接
}
return html;
}



代码完毕!

看到这如果没有遇到任何问题的基本上不用往下看了。

上面的那个程序是请求百度的首页,返回的html页面是正常的,不会乱码,可能你在换几个网站,返回的html页面还不是乱码。就这样在暗自得意的时候,不经意间遇到了一个URL地址,你再用上面的程序,结果他给你返回的是乱码。检查了好半天,编码什么的都正确。到底为什么还会乱码?后来仔细查看一下原来server端给你返回的是gzip格式的压缩网页,而不是普通的html页面。这样终于想明白了。最后进行进行代码修正。

String html = null;
HttpHost proxy = null;
proxy = new HttpHost(“10.221.41.192”,808 "http");

DefaultHttpClient httpClientOld = new DefaultHttpClient();// 创建httpClient对象
DecompressingHttpClient httpClient = new DecompressingHttpClient(httpClientOld);//避免返回compressed格式的Entity出现乱码
try {
URL url = new URL(pageUrl);
URI uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);// 防止pageUrl中出现空格等特殊字符导致请求失败
HttpGet httpget = new HttpGet(uri);// 以get体式格式请求该URL
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
HttpResponse responce = httpClient.execute(httpget);// 获得responce对象
int resStatu = responce.getStatusLine().getStatusCode();// 返回码
if (resStatu == HttpStatus.SC_OK) {// 200正常 其它就不合错误
HttpEntity entity = responce.getEntity(); // 获得响应实体


if (entity != null) {
html = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset().toString());// 对返回的html代码进行解析转码
}
} else {
System.out.println("状态返回异常");
}
} catch (Exception e) {
log.error(e.toString());
} finally {
httpClient.getConnectionManager().shutdown();
}
return html;

相关主题