java + httpclient +post请求的示例分析

小编给大家分享一下java + httpclient +post请求的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

public void testMethodpost(){
//初始化http请求
CloseableHttpClient httpclient=HttpClientBuilder.create().build();
String url = "xxxxxxxxxxxxx";
//初始化http请求
HttpPost post=new HttpPost(url);
//设置请求头
post.setHeader("Content-Type","application/json;charset=UTF-8");
try {

        String paramJson="{\"userName\":\"xxxxxxx\",\"passWord\":\"JVGK+jDLU7\"}";

//          JSONObject jsonObject = JSON.parseObject(paramJson);
//
//            System.out.println(jsonObject);

//            String param=JSON.toJSONString(jsonObject);

        // 提交参数发送请求
        StringEntity requestEntity = new StringEntity(paramJson,"UTF-8");

       post.setEntity(requestEntity);
         CloseableHttpResponse response=httpclient.execute(post);

        HttpEntity entity=response.getEntity();
        String entityStr =EntityUtils.toString(entity,"UTF-8");
        System.out.println(entityStr);
        //httpclient.close();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

遇到的坑:
1.前期使用POST数据时,用了UrlEncodedFormEntity()这个方法
结果服务器返回500,打印的请求参数为:key=value&key2=value2格式

解决办法:使用 StringEntity requestEntity = new StringEntity(paramJson,"UTF-8");办法解决

以上是“java + httpclient +post请求的示例分析”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!