1. 程式人生 > >java + httpclient +post請求(記錄下)

java + httpclient +post請求(記錄下)

服務 ati -type eth catch xxxxxxxx name util eat

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請求(記錄下)