package com.qianbaocard.vinci.tc.web.rest.util; 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.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.springframework.stereotype.Component; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Created by LiSenMao on 2018/5/5. */ @Component public class HttpClientUtil { public static final String CHARSET = "UTF-8"; public static String doPostKeyValue(String url, Map<String, String> map) { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); HttpPost httpPost; CloseableHttpResponse response = null; String result = null; try { httpPost = new HttpPost(url); //設置參數 List<NameValuePair> list = new ArrayList<>(); map.forEach((k, v) -> list.add(new BasicNameValuePair(k, v))); UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, CHARSET); /* * 注意,必定要加,默認就是application/x-www-form-urlencoded,可是、可是、可是 * 不加,服務器收不到參數 * */ entity.setContentType("application/x-www-form-urlencoded"); httpPost.setEntity(entity); response = httpClient.execute(httpPost); if (response != null) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result = EntityUtils.toString(resEntity, CHARSET); } } } catch (Exception ex) { ex.printStackTrace(); } finally { if (response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } public static void main(String[] args) { Map<String, String> map = new HashMap<>(); map.put("client_id", "xxx"); map.put("access_token", "xxx"); map.put("machine_code", "xxx"); System.out.println(doPostKeyValue("https://xxx", map)); } }
去看UrlEncodedFormEntity的源碼:java
/** * Constructs a new {@link UrlEncodedFormEntity} with the list * of parameters in the specified encoding. * * @param parameters list of name/value pairs * @param charset encoding the name/value pairs be encoded with * @throws UnsupportedEncodingException if the encoding isn't supported */ public UrlEncodedFormEntity ( final List <? extends NameValuePair> parameters, final String charset) throws UnsupportedEncodingException { super(URLEncodedUtils.format(parameters, charset != null ? charset : HTTP.DEF_CONTENT_CHARSET.name()), ContentType.create(URLEncodedUtils.CONTENT_TYPE, charset)); }
接着查看CONTENT_TYPE :web
/** * The default HTML form content type. */ public static final String CONTENT_TYPE = "application/x-www-form-urlencoded";
沒搞明白,爲何默認參數就是application/x-www-form-urlencoded,還非要我去指定一下,否則,服務器就接收不到參數。spring