2018-05-01

记录一下使用中关于HttpClient以及Json传递的坑
HTTPS:
普通方式:
public class Test(){
      URI uri = newURIBuilder().setScheme("http")
                .setHost("***:**").setPath("/***/***").build();
      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpPost httpPost = newHttpPost(uri);
      httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
      List params = newArrayList();
      params.add(newBasicNameValuePair("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(finallURI uri, finallList params)
                               throwsClientProtocolException,
                               IOException,                                                   
                               NoSuchAlgorithmException,KeyManagementException {
        String result = null;
        SSLContext sslContext = SSLContext.getInstance("SSL");
        // set up a TrustManager that trusts everything
        sslContext.init(null, newTrustManager[] { 
        newX509TrustManager() {

        publicX509Certificate[] getAcceptedIssuers() {
             return null;
        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {

        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {

        }

        } }, newSecureRandom());

        CloseableHttpClient httpclient = HttpClients.custom().
                          setSSLSocketFactory(newSSLSocketFactory(sslContext)).build();
        HttpPost httpPost = newHttpPost(uri);
        httpPost.addHeader("Content-type", "application/json");
        httpPost.setEntity(newUrlEncodedFormEntity(params));
        CloseableHttpResponse response = httpclient.execute(httpPost);
        try{
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } finally{
            response.close();
        }
        returnresult;
    }

        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, @RequestBodyString request) {
      JSONObject requestJson = JSON.parseObject(request);
}

这里需要说明的是@RequestBody需要接的参数是一个string化的json,而不是一个json对象,
也可以用对象类型来接收。
Reference:
1. http://blog.csdn.net/mack415858775/article/details/52388484
2. http://blog.csdn.net/g1248019684/article/details/50850386
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Binner阅读 3,184评论 0 48
  • 2018年4月总结 写月度总结是为了下月目标更有效的实现。 你对本月自己的表现满意吗?(五颗星代表非常满意) 不满...
    营养私教西西阅读 3,157评论 8 7
  • 意志力,微习惯,班主任读书,然后讲给学生,全班学习,一次在根源处改变班风学风。 每天5点起床的人都怎么样了ppt ...
    嘎嘎嘎嘎黄小鸭阅读 1,631评论 0 0
  • 董沛沛 洛阳 焦点讲师班三期 坚持原创分享第343天 习惯具有强大的力量有调查表明,人们日常活动的90%源自习惯...
    缘源流长阅读 1,534评论 0 0
  • 20180501,戒的第一天。加油!
    eide阅读 994评论 0 0