httpclient 傳送post請求
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
3、建立引數佇列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams,
httppost.setEntity(uefEntity);
4、傳送http請求
CloseableHttpResponse response = httpclient.execute(httppost);
5、獲取響應資料
HttpEntity entity = response.getEntity();
6. 釋放連線
httpclient.close();