码迷,mamicode.com
首页 > 编程语言 > 详细

java + httpclient +post请求(记录下)

时间:2019-04-01 11:51:14      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:json   protoc   param   prot   str   The   toc   遇到   ring   

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请求(记录下)

标签:json   protoc   param   prot   str   The   toc   遇到   ring   

原文地址:https://blog.51cto.com/12390959/2372182

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!