最近HttpClient用的比较多,应用中有些需要注意的地方。
生成HttpClient的地方:
httpClient=new HttpClient();
httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
//一定要有,否则会生成多个Cookie header送给web server
httpClient.getParams().setParameter("http.protocol.single-cookie-header",true);
httpClient.getParams().setParameter("http.protocol.content-charset","gb2312");
ArrayList headerList=new ArrayList();
Header accept=new Header("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/x-silverlight, */*");
headerList.add(accept);
......
httpClient.getParams().setParameter("http.default-headers",headerList);
httpClient.getParams().setParameter("http.protocol.version",HttpVersion.HTTP_1_1);
httpClient.getParams().setParameter("http.method.retry-handler",new DefaultHttpMethodRetryHandler());
生成httpMethod的地方:
PostMethod postMethod =new PostMethod();
postMethod.getParams().setUriCharset("GB2312");
postMethod.setURI(new URI(url,false,"GB2312"));
client.executeMethod(postMethod);
以上可避免送出类似“HTTP://127.0.0.1:8080/action.do?content=一二三四五六”的URL时出现URI报错