java 使用httpclient出错org.apache.http.client.ClientProtocolException

时间:2022-03-01 08:27:11

以下是我用httpclient写的一个方法

public static void GetFromServer(String url)

{

HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
retStr = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(url);
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();


return "";
}
return retStr;

}

url 为正常的路径时,这段代码是没问题,retStr能得到正确的url返回值,但一旦访问的url要经过代理或者需要经过注册访问的时候,比如url:
http://list.tmall.com/search_product.htm?spm=a220m.1000858.0.0.pCYtHr&cat=51260020&s=119&sort=s&style=g&search_condition=48&from=sn_1_cat&active=1&new=1&shopType=any&industryCatId=51260020&type=pc#J_Filter

当用上面的url作为参数时,出现以下错误

org.apache.http.client.ClientProtocolException

at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:909)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)

. . . . . 

. . . . . 

Caused by: org.apache.http.HttpException: Unable to establish route: planned = {s}->https://pass.tmall.com; current = {s}->https://login.taobao.com
at org.apache.http.impl.client.DefaultRequestDirector.establishRoute(DefaultRequestDirector.java:842)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:645)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:480)

at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)

解决办法:加上ClientConnectionManager到httpclient中去

public static void GetFromServer(String url)

{

ClientConnectionManager connManager = new PoolingClientConnectionManager();
DefaultHttpClient client = new DefaultHttpClient(connManager);

HttpGet get = new HttpGet(url);
try {
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
retStr = EntityUtils.toString(entity);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(url);
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();


return "";
}
return retStr;

}