本博客是java环境下,借助httpclient实现项目间接口的调用,包括POST\GET请求;还有可将GET参数转换拼接成RESFUL规范的GET请求。

每一步有详细的介绍,从httpclient创建、传参、header、请求后返参获取结果等详细介绍。还有额外的basic auth校验也有,可以直接在POSTMAN获取转换后的参数。

1、GET请求

url是你对应要请求的URL地址;param对应的是需要添加的请求参数,可根据实际情况增加;
在header设置里加了个basic auth校验;可根据实际情况使用;

实现代码如下:

/**
    * 发送get请求
    *
    * @param url   路径
    * @param param 请求参数
    * @return
    * @throws ParseException
    * @throws IOException
    */
	public String getInfo(String url,String param) throws IOException, NoSuchAlgorithmException, URISyntaxException {
        String body = "";
        //httpclient创建
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder uri = new URIBuilder(url);
        //将请求参数先统一放进list里
        List<NameValuePair> list = new LinkedList<>();
        BasicNameValuePair param1 = new BasicNameValuePair("param",param);
        list.add(param1);
        //将参数拼接到url
        uri.setParameters(list);
        //创建get方式请求对象
        HttpGet httpGet = new HttpGet(uri.build());
        //basic auth校验 ,可根据实际情况添加
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Basic xxx");
        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpGet);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if (entity != null) {
        	//按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "UTF-8");
        }
        EntityUtils.consume(entity);
        log.info(String.format("response:%s",response));
        log.info(String.format("response-body:%s",body));
        response.close();
        return body;
    }

2、POST请求

url是你对应要请求的URL地址;jsonObject 是POST请求的传参体,也可以直接在函数里将参数传给“body”。

实现代码如下:

/**
    * 发送post请求
    *
    * @param url        路径
    * @param jsonObject 参数(json类型)
    * @return
    * @throws ParseException
    * @throws IOException
    */
   public String sendPOST(String url, JSONObject jsonObject) throws ParseException, IOException {
      String body = "";
      //创建httpclient对象
      CloseableHttpClient client = HttpClients.createDefault();
      //创建post方式请求对象
      HttpPost httpPost = new HttpPost(url);
      //装填参数
      //StringEntity s = new StringEntity(jsonObject.toString(), "UTF-8");
      StringEntity s = new StringEntity(body, "UTF-8");
      s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
            "application/json"));
      //将设置参数到请求对象中
      httpPost.setEntity(s);
      //设置header信息,指定报文头【Content-type】
      httpPost.setHeader("Content-type", "application/json");
      //执行请求操作,并拿到结果(同步阻塞)
      CloseableHttpResponse response = client.execute(httpPost);
      //获取结果实体
      HttpEntity entity = response.getEntity();
      if (entity != null) {
         //按指定编码转换结果实体为String类型
         body = EntityUtils.toString(entity, "UTF-8");
      }
      EntityUtils.consume(entity);
      log.info(String.format("response:%s",response));
      log.info(String.format("response-body:%s",body));
      //关闭释放链接
      response.close();
      return body;
   }

3、RESFUL接口

此处是实现RESFUL接口的GET请求。
利用正则匹配将原本的URL转换成RESFUL规范的URL来请求。

url是你对应要请求的URL地址;param对应的是需要添加的请求参数,可根据实际情况增加;
在header设置里加了个basic auth校验;可根据实际情况使用;

RESFUL规范介绍:https://www.qycn.com/xzx/article/14355.html

实现代码如下:

//利用该函数将原本的url转换为resful规范的url
	public static String matcherUrl(String url, Map<String, String> param) {
        String regex = "(?=\\{).*?(\\})";
        String fieldRegex = "\\{|\\}";
        //创建一个模式对象
        Pattern pattern = Pattern.compile(regex);
        //匹配字符串中的已编译模式
        Matcher matcher = pattern.matcher(url);
        List<String> fields = new ArrayList<>();
        while (matcher.find()) {
            fields.add(matcher.group());
        }

        if (!fields.isEmpty()) {
            for (String field : fields) {
                url = url.replace(field, param.getOrDefault(field.replaceAll(fieldRegex, ""),""));
            }
        }
        return url;
    }

/**
    * 发送get请求
    *
    * @param url   路径
    * @param param 请求参数
    * @return
    * @throws URISyntaxException
    * @throws NoSuchAlgorithmException
    * @throws IOException
    */
    public String getInfoResful(String url, String param1, String param2) throws URISyntaxException, NoSuchAlgorithmException, IOException {
        String body = "";
        //创建httpclient对象
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder builder = new URIBuilder(url);
        //将请求参数先装填进map
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("param1",param1);
        paramMap.put("param2",param2);
        paramMap.put("param3","string");
        URI uri = builder.build();
        //将url转换成resful规范的
        String uriStr = matcherUrl(uri+"/{param1}/{param2}/{param3}", paramMap);
        //创建get方式请求对象
        HttpGet httpGet = new HttpGet(uriStr);
        log.info(String.format("URL:%s", uriStr));
        //basic auth校验 ,可根据实际情况添加
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Basic xxx");
        //执行请求操作,并拿到结果(同步阻塞)
        CloseableHttpResponse response = client.execute(httpGet);
        //获取结果实体
        HttpEntity entity = response.getEntity();
        if(entity != null){
            //按指定编码转换结果实体为String类型
            body = EntityUtils.toString(entity, "UTF-8");
        }
        EntityUtils.consume(entity);
        log.info(String.format("response:%s", response));
        log.info(String.format("response-body:%s", body));
        response.close();
        return body;
    }