须要依赖如下架包: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; }