HttpClient及JSON的這些坑你踩到過嗎?

JSON Scheme 技術 IT碼農說 IT碼農說 2017-10-02

HttpClient及JSON的這些坑你踩到過嗎?

HTTPS:

普通方式:

記錄一下使用中關於HttpClient以及Json傳遞的坑。

public class Test {public static void main(String[] args) throws Exception {URI uri = new URIBuilder().setScheme("http").setHost("***:**").setPath("/***/***").build();HttpClient httpClient = HttpClientBuilder.create().build();HttpPost httpPost = new HttpPost(uri);httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");List<NameValuePair> params = new ArrayList<NameValuePair>();params.add(new BasicNameValuePair("params", "test"));HttpResponse httpResponse = httpClient.execute(httpPost);StatusLine httpStatus = httpResponse.getStatusLine();HttpEntity httpEntity = httpResponse.getEntity();System.out.println("httpStatusline: " + httpStatus);System.out.println("strEntity: " + EntityUtils.toString(httpEntity));EntityUtils.consume(httpEntity);}}

這種適合普通的http的請求,當把Scheme換成https時,

報錯:

sun.security.validator.ValidatorException: PKIX path building failed

客戶端沒有證書,可以在代碼中跳過證書驗證。

public static String sendPost(final URI uri,final List<NameValuePair> params) throws ClientProtocolException,IOException,NoSuchAlgorithmException,KeyManagementException {String result = null;SSLContext sslContext = SSLContext.getInstance("SSL");// set up a TrustManager that trusts everythingsslContext.init(null, new TrustManager[] { new X509TrustManager() {public X509Certificate[] getAcceptedIssuers() {return null;}public void checkClientTrusted(X509Certificate[] certs, String authType) {}public void checkServerTrusted(X509Certificate[] certs, String authType) {}} }, new SecureRandom());CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(new SSLSocketFactory(sslContext)).build();HttpPost httpPost = new HttpPost(uri);httpPost.addHeader("Content-type", "application/json");httpPost.setEntity(new UrlEncodedFormEntity(params));CloseableHttpResponse response = httpclient.execute(httpPost);try {HttpEntity entity = response.getEntity();result = EntityUtils.toString(entity);EntityUtils.consume(entity);} finally {response.close();}return result;}

request.getParameter無法得到appliation/json的數據

@ResponseBody@RequestMapping(value = "/**/**.json", method = RequestMethod.POST)public String valiate(ModelMap map, HttpServletRequest request) {System.out.println(request.getParameter("param"));}

這種方式無法得到Content-Type是appliation/json的數據。

這種方式適合Content-Type為application/x-www-form-urlencoded的請求。

解決:

@ResponseBody@RequestMapping(value = "/**/**.json", method = RequestMethod.POST )public String valiate(ModelMap map, @RequestBody String request) {JSONObject requestJson = JSON.parseObject(request);}

這裡需要說明的是@RequestBody需要接的參數是一個string化的json,而不是一個json對象,也可以用對象類型來接收。

相關推薦

推薦中...