httpclient post請求帶參數返回數據亂碼問題解決


 

客戶端代碼:

//帶參數的post請求
    @Test
    public void doPostWithParam() throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //創建一個post對象
        HttpPost post = new HttpPost("http://localhost:8082/httpclient/post.action");
        //模擬一個表單
        List<NameValuePair> kvList = new ArrayList<NameValuePair>();
        kvList.add(new BasicNameValuePair("username", "張三"));
        kvList.add(new BasicNameValuePair("password", "123"));
        //包裝成一個Entity對象(后面加字符集是為了向服務端發送數據時不會亂碼)
        StringEntity paramEntity = new UrlEncodedFormEntity(kvList,"utf-8");
        //設置請求內容
        post.setEntity(paramEntity);
        //執行post請求
        CloseableHttpResponse response = httpClient.execute(post);
        HttpEntity rtnEntity = response.getEntity();
        String string = EntityUtils.toString(rtnEntity, "utf-8");
        System.out.println(string);
        response.close();
        httpClient.close();
    }

 

服務端Controller代碼:

    //mapping后面加produces是為了返回數據給接口調用者時不會亂碼
    @RequestMapping(value="/httpclient/post",method=RequestMethod.POST,
            produces=MediaType.TEXT_PLAIN_VALUE+";charset=utf-8")
    @ResponseBody
    public String testPost(String username,String password) {
        String result = "username: "+username + "\tpassword: "+password;
        System.out.println(result);
        return result;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM