简介
HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。
使用步骤
- 创建HttpClient对象,可以使用HttpClients.createDefault();
- 创建HttpPost或者HttpGet对象;
- 创建HttpResponse,调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse;
- 释放连接。
实战代码
- 引入jar包

- 无参数GET请求

- 有参数GET请求
URI uri = new URIBuilder("http://www.baidu.com").setParameter("wd", "java").build();
HttpGet httpGet = new HttpGet(uri);
- 有参数POST请求
HttpPost httpPost = new HttpPost("http://www.baidu.com");
httpPost.setEntity(new StringEntity(stringContent));
HttpPost httpPost = new HttpPost("http://www.baidu.com");
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair("scope", "project"));
parameters.add(new BasicNameValuePair("q", "java"));
// 构造一个form表单式的实体
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
httpPost.setEntity(formEntity);