httpclient 获取到网页内容乱码问题

最近在爬一些页面 碰到解析的内容有乱码 最后这个方法解决了这个乱码问题
public static String getHTMLByDeCode(String url, String... params) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
int index = 0;
if(ipPortList.size() != 0){
index = (int) (Math.random() * ipPortList.size() );
String ipPort = ipPortList.get(index);
if(!StringUtil.isEmpty(ipPort))
{
logger.debug(index+">>>"+ipPort);
String[] ipPortResult = ipPort.split(":");
HttpHost proxy = new HttpHost(ipPortResult[0], Integer.parseInt(ipPortResult[1]));//设置代理ip
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
}
HttpProtocolParams.setUserAgent(httpClient.getParams(),"Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.1.9) Gecko/20100315 Firefox/3.5.9");
String charset = "UTF-8";
if (null != params && params.length >= 1) {
charset = params[0];
}
HttpGet httpget = new HttpGet();
String content = "";
try{
httpget.setURI(new java.net.URI(url));
HttpResponse response = httpClient.execute(httpget);
HttpEntity entity = response.getEntity();
if (entity != null) {
// 使用EntityUtils的toString方法,传递默认编码,在EntityUtils中的默认编码是ISO-8859-1
content = EntityUtils.toString(entity, charset);
httpget.abort();
httpClient.getConnectionManager().shutdown();
}
}
catch(Exception e){
if(ipPortList.size() != 0)
ipPortList.remove(index);

e.printStackTrace();
logger.debug("get proxy again!!!!");
getHTMLByDeCode(url,params);
}
return content;
}



参考网址:
http://dh189.iteye.com/blog/732111
http://mhqawjh.iteye.com/blog/473450
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值