/** * post請求 * @param url * @param json * @return */ public static JSONObject doPost(String url,JSONObject json){ CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); JSONObject response = null; try { StringEntity s = new StringEntity(json.toString()); s.setContentEncoding("UTF-8"); s.setContentType("application/json");//發送json數據需要設置contentType post.setEntity(s); HttpResponse res = httpclient.execute(post); if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){ String result = EntityUtils.toString(res.getEntity());// 返回json格式: response = JSONObject.fromObject(result); } } catch (Exception e) { throw new RuntimeException(e); } return response; }
maven依賴包:
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>