代碼實現:
/** * 向指定 URL 發送POST方法的請求(數據格式為json) * * @param url 發送請求的 URL * @param paramMap 請求參數集合 * @param paramMap 請求參數,請求參數為json的形式。 * @return 所代表遠程資源的響應結果 */ public static String sendPost(String url, Map<String, Object> paramMap) { CloseableHttpClient httpClient = null; CloseableHttpResponse httpResponse = null; String result = ""; // 創建httpClient實例 httpClient = HttpClients.createDefault(); // 創建httpPost遠程連接實例 HttpPost httpPost = new HttpPost(url); // 配置請求參數實例 RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000)// 設置連接主機服務超時時間 .setConnectionRequestTimeout(35000)// 設置連接請求超時時間 .setSocketTimeout(60000)// 設置讀取數據連接超時時間 .build(); // 為httpPost實例設置配置 httpPost.setConfig(requestConfig); // 設置請求頭 httpPost.addHeader("Content-Type", "application/json"); httpPost.addHeader("appid", "avkp4qyu01fki"); // 封裝post請求參數 JSONObject jsonObject = new JSONObject(); if (null != paramMap && paramMap.size() > 0) { //List<NameValuePair> nvps = new ArrayList<NameValuePair>(); // 通過map集成entrySet方法獲取entity Set<Map.Entry<String, Object>> entrySet = paramMap.entrySet(); // 循環遍歷,獲取迭代器 Iterator<Map.Entry<String, Object>> iterator = entrySet.iterator(); while (iterator.hasNext()) { Map.Entry<String, Object> mapEntry = iterator.next(); //nvps.add(new BasicNameValuePair(mapEntry.getKey(), mapEntry.getValue().toString())); jsonObject.put(mapEntry.getKey(),mapEntry.getValue()); } ContentType contentType = ContentType.create("application/json"); // 為httpPost設置封裝好的請求參數 try { //設置參數的content-type格式 httpPost.setEntity(new StringEntity(jsonObject.toString(), contentType)); //此方式參數content-type為application/x-www-form-urlencoded,源碼中默認實現的 //httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8")); } catch (Exception e) { e.printStackTrace(); } } try { // httpClient對象執行post請求,並返回響應參數對象 httpResponse = httpClient.execute(httpPost); // 從響應對象中獲取響應內容 HttpEntity entity = httpResponse.getEntity(); result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // 關閉資源 if (null != httpResponse) { try { httpResponse.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } ———————————————— 版權聲明:本文為CSDN博主「gxk2019」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。 原文鏈接:https://blog.csdn.net/gxkvji/article/details/97966198
通過HttpservletRequest接收json數據
// 接收json數據 BufferedReader streamReader = new BufferedReader(new InputStreamReader( req.getInputStream(), "UTF-8")); StringBuilder responseStrBuilder = new StringBuilder(); String inputStr; while ((inputStr = streamReader.readLine()) != null) responseStrBuilder.append(inputStr); // 轉化成json對象 JSONObject jsonObject = JSONObject.fromObject(responseStrBuilder .toString());