1. 程式人生 > >HttpClient post方式,新增請求引數

HttpClient post方式,新增請求引數

    import org.apache.http.HttpEntity;
    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.apache.http.util.EntityUtils; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; /** * Created by shengjk1 on 2016/5/23. */
public class Test { @org.junit.Test public void requestByPostMethod() { CloseableHttpClient httpClient = getHttpClient(); try { HttpPost post = new HttpPost("http://localhost:8088/match"); //這裡用上本機的某個工程做測試 //建立引數列表 List<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("idCard", "1234567890")); list.add(new BasicNameValuePair("name", "張三1")); list.add(new BasicNameValuePair("cardType", "ID")); list.add(new BasicNameValuePair("invoker", "RI")); list.add(new BasicNameValuePair("period", "240")); //url格式編碼 UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(list, "UTF-8"); post.setEntity(uefEntity); System.out.println("POST 請求...." + post.getURI()); //執行請求 CloseableHttpResponse httpResponse = httpClient.execute(post); try { HttpEntity entity = httpResponse.getEntity(); if (null != entity) { System.out.println("-------------------------------------------------------"); System.out.println(EntityUtils.toString(entity)); System.out.println("-------------------------------------------------------"); } } finally { httpResponse.close(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { closeHttpClient(httpClient); } catch (Exception e) { e.printStackTrace(); } } } private CloseableHttpClient getHttpClient() { return HttpClients.createDefault(); } private void closeHttpClient(CloseableHttpClient client) throws IOException { if (client != null) { client.close(); } } }