溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

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

發布時間:2021-11-24 10:24:15 來源:億速云 閱讀:358 作者:小新 欄目:軟件技術

小編給大家分享一下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請求的示例分析”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女