HttpClient相比于jdk自带的URLConnection更加灵活,用起来也比较方便,它使客户端发送http请求更加方便,提高了开发效率。
使用HttpClient发送请求接受返回参数,其步骤大致如下
1、创建HttpClient对象
// 创建默认的httpClient实例
CloseableHttpClient httpclient = HttpClients.createDefault();
2、创建请求方法的实例(以post请求为例)
URL url=new URL(”https://www.baidu.com");
HttpPost httppost = new HttpPost(url);
3、创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
4、发送http请求
CloseableHttpResponse response = httpclient.execute(httppost);
5、获取响应数据
HttpEntity entity = response.getEntity();
6. 释放连接
httpclient.close();