apache-httpclient 快速使用
HttpClient 是 Apache Jakarta Common下的子项目,用于提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,支持 HTTP1.0 和 HTTP 1.1,支持 HTTP 的全部方法(GET,POST,PUT,DELETE 等);
HttpClient 官网:
http://hc.apache.org/httpcomponents-client-4.5.x/index.html
使用 HttpClient 需要导入以下依赖:
org.apache.httpcomponents:httpclient
发送 GET 请求
CloseableHttpClient httpclient = HttpClients.createDefault(); //构建默认HttpClient对象
HttpGet httpGet = new HttpGet("http://blog.csdn.net/");
//如果要设置发送头,可以通过 httpGet.setHeader(String name, String value) 方法
CloseableHttpResponse response = httpclient.execute(httpGet); //执行HttpClinet,获取HttpResponse 对象
//获取响应状态行
System.out.println(response.getStatusLine());
//获取响应头
Header[] headers = response.getAllHeaders();
Arrays.stream(headers).forEach(System.out::println);
//获取响应实体
HttpEntity entity = response.getEntity();
System.out.println(entity.getContentLength()); //获取响应正文长度
//以字符流的方式读取响应正文
String content = new BufferedReader(new InputStreamReader(entity.getContent())).lines().collect(Collectors.joining("\n"));
System.out.println(content);
发送 POST 请求
//构建默认HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("http://127.0.0.1:8080/checkLogin");
//构建请求参数
Map<String,String> params = new HashMap<>();
params.put("username","assad");
params.put("password","1234");
List<NameValuePair> formparams = new ArrayList<>();
for(Map.Entry<String,String> entry : params.entrySet())
formparams.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
UrlEncodedFormEntity encodedEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
httpPost.setEntity(encodedEntity);
//执行HttpClinet,获取HttpResponse 对象
CloseableHttpResponse response = httpClient.execute(httpPost);
//如果要设置发送头,可以通过 httpGet.setHeader(String name, String value) 方法
//获取响应状态行
System.out.println(response.getStatusLine());
//获取响应头
Header[] headers = response.getAllHeaders();
Arrays.stream(headers).forEach(System.out::println);
//获取响应实体
HttpEntity entity = response.getEntity();
System.out.println(entity.getContentLength()); //获取响应正文长度
//以字符流的方式读取响应正文
String content = new BufferedReader(new InputStreamReader(entity.getContent())).lines().collect(Collectors.joining("\n"));
System.out.println(content);