須要依賴如下架包:java
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.5</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpcore --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.9</version> </dependency>
get請求和post請求工具apache
/** * get請求工具類 * @param url * @return */ public static JSONObject doGetStr(String url){ //建立HTTP請求客戶端 CloseableHttpClient httpclient = HttpClientBuilder.create().build(); //建立HTTP get請求 HttpGet httpGet = new HttpGet(url); //建立返回結果 JSONObject jsonObject = null; //獲取響應結果 try { HttpResponse response = httpclient.execute(httpGet); //獲取消息體中的結果 HttpEntity entity = response.getEntity(); if(entity != null){ String strEntity = EntityUtils.toString(entity,"UTF-8"); jsonObject = JSONObject.fromObject(strEntity); } } catch (Exception e) { System.out.println(new Date()+"GET請求失敗"); return null; } return jsonObject; }
/** * POST請求工具類 */ public static JSONObject doPostStr(String url,String strOut){ //建立HTTP請求客戶端 CloseableHttpClient httpclient = HttpClientBuilder.create().build(); //建立Post請求 HttpPost httpPost = new HttpPost(url); //建立返回結果 JSONObject jsonObject = null; //設置請求參數 try { httpPost.setEntity(new StringEntity(strOut,"UTF-8")); HttpResponse response = httpclient.execute(httpPost); //獲取消息體中的結果 HttpEntity entity = response.getEntity(); if(entity != null){ String strEntity = EntityUtils.toString(entity,"UTF-8"); jsonObject = JSONObject.fromObject(strEntity); } } catch (Exception e) { System.out.println(new Date()+"POST請求失敗"); return null; } return jsonObject; }