小編給大家分享一下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請求的示例分析”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。