客戶端代碼:
//帶參數的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; }