Java HttpPost請求基於apache的httpclient

<span style="font-family: Arial, Helvetica, sans-serif;">/**</span>
* 發送 post請求訪問本地應用並根據傳遞參數不同返回不同結果
*/
public static void post(String url, List<BasicNameValuePair> formparams) {
// 創建默認的httpClient實例.
CloseableHttpClient httpclient = HttpClients.createDefault();


// 創建httppost
HttpPost httppost = new HttpPost(url);
// 創建參數隊列


UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
httppost.setEntity(uefEntity);
System.out.println("executing request" + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
HttpEntity entity = response.getEntity();
if (entity != null) {
System.out.println("--------------------------------------");
System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
System.out.println("--------------------------------------");
}
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 關閉連接,釋放資源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章