1、maven引入
org.apache.httpcomponents httpclient 4.5 org.apache.httpcomponents httpcore 4.4.4 2、封装post请求方法 public static String httpPost(String url,Map map){ // 返回body String body = null; // 获取连接客户端工具 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse=null; // 2、创建一个HttpPost请求 HttpPost post = new HttpPost(url); // 5、设置header信息 org.apache.httpcomponents httpmime 4.5
/**header中通用属性*/ post.setHeader("Accept","*/*"); post.setHeader("Accept-Encoding","gzip, deflate"); post.setHeader("Cache-Control","no-cache"); post.setHeader("Connection", "keep-alive"); post.setHeader("Content-Type", "application/json;charset=UTF-8"); /**业务参数*/ post.setHeader("test1","test1"); post.setHeader("test2",2);
// 设置参数 if (map != null) { //System.out.println(JSON.toJSONString(map)); try { StringEntity entity1=new StringEntity(JSON.toJSONString(map),"UTF-8"); entity1.setContentEncoding("UTF-8"); entity1.setContentType("application/json"); post.setEntity(entity1); // 7、执行post请求操作,并拿到结果 httpResponse = httpClient.execute(post); // 获取结果实体 HttpEntity entity = httpResponse.getEntity(); if (entity != null) { // 按指定编码转换结果实体为String类型 body = EntityUtils.toString(entity, "UTF-8"); } try { httpResponse.close(); httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); } } return body; } 3、封装GET请求方法
public static String httpGet(String url){ // 获取连接客户端工具 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse httpResponse=null; String finalString = null; HttpGet httpGet = new HttpGet(url); /**公共参数添加至httpGet*/
/**header中通用属性*/ httpGet.setHeader("Accept","*/*"); httpGet.setHeader("Accept-Encoding","gzip, deflate"); httpGet.setHeader("Cache-Control","no-cache"); httpGet.setHeader("Connection", "keep-alive"); httpGet.setHeader("Content-Type", "application/json;charset=UTF-8"); /**业务参数*/