HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。本文首先介绍 HTTPClient,然后根据作者实际工作经验给出了一些常见问题的解决方法。
HttpClient 功能介绍
- 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
- 支持自动转向
- 支持 HTTPS 协议
- 支持代理服务器等
@Test
public void asearchTest() {
String url =“”;
Executor executor = Executor.newInstance();
Form form = Form.form();
form.add("fullnameCn", "张三");
form.add("identityNumber", "");
form.add("mobile", "");
try {
UrlEncodedFormEntity urlencEntity = new UrlEncodedFormEntity(
form.build(), "UTF-8");
Request request = Request.Post(url);
Response response = executor.execute(request.body(urlencEntity));
String rtn = response.returnContent().asString();
System.out.println("rtn=================== begin");
System.out.println(rtn);
System.out.println("rtn------------------- end");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void asearch() throws ClientProtocolException, IOException {
String url = “”;
CloseableHttpClient chc = HttpClients.createDefault();
List<NameValuePair> list = new ArrayList<NameValuePair>();
NameValuePair pair1 = new BasicNameValuePair("fullnameCn", "张三");
NameValuePair pair2 = new BasicNameValuePair("identityNumber", "");
NameValuePair pair3 = new BasicNameValuePair("mobile", "");
list.add(pair1);
list.add(pair2);
list.add(pair3);
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
HttpPost post = new HttpPost(url);
post.setEntity(entity);
HttpResponse response = chc.execute(post);
String strResult = EntityUtils.toString(response.getEntity());
System.out.println("rtn=================== begin");
System.out.println(strResult);
System.out.println("rtn------------------- end");
}
@Test
public void testPost() {
String url = “”;
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
Form form = Form.form();
form.add("fullnameCn", "张三");
form.add("identityNumber", "");
form.add("mobile", "");
try {
httpPost.setEntity(new UrlEncodedFormEntity(form.build(), "UTF-8"));
CloseableHttpResponse response2 = httpclient.execute(httpPost);
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
String rtn = EntityUtils.toString(entity2, "UTF-8");
System.out.println("--------------------rtn begin");
System.out.println(rtn);
System.out.println("====================rtn end");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}