封裝post的請求
1、通過httpclient發送post請求進行連接
2、對於post請求,包含兩個部分,url和要傳的參數
3、url我們在測試的時候是知道的,關鍵是參數如何進行傳輸。對於post請求,我們使用NameValuePair類型進行傳輸。
4、釋放連接
package test1; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.testng.annotations.Test; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by daojia on 2017-6-20. * 模擬httpsend請求,傳入的參數有url以及附帶的參數,返回String類型 */ public class httptest { public String send(String url,Map<String,String> map) throws IOException { String result = ""; //創建httpclient對象 CloseableHttpClient client = HttpClients.createDefault(); //創建post請求對象 HttpPost httpPost = new HttpPost(url); //裝填參數 List<NameValuePair> parm = new ArrayList<NameValuePair>(); if(map != null) { for(Map.Entry<String,String> me : map.entrySet()) { parm.add(new BasicNameValuePair(me.getKey(),me.getValue())); } } System.out.println("請求參數"+parm.toString()); httpPost.setEntity(new UrlEncodedFormEntity(parm,"utf-8")); System.out.println("請求鏈接"+httpPost.toString()); //執行請求 CloseableHttpResponse response = client.execute(httpPost); result=response.toString(); System.out.println("請求鏈接"+result);
response.close(); return result; }