前言
最近调用公司项目一个接口时,发现该接口是一个Get请求,入参在Body 中(json格式)。场景如下:A服务需发送http请求调用B服务的接口(该接口为Get方式,入参是一个json字符串在body中传递)
当我看到这个接口的时候,感觉好奇怪(MMP,干嘛不用POST请求。Get就get,请求还放Body中,心里有些不爽)尽管心里不爽,但是也只能默默接受,撸起袖子 “干” 就完了!

实现过程:
首先官方不推荐这样做,但是http(基于tcp的超文本传输协议)并没有规定,Get 请求不能加body
一.首先我写了一个Get请求接口,本地测试一下,便于大家直观的理解

调用成功:

本地使用postman调用是成功的,接下来我们使用Java代码请求调用
二.使用Http工具类调用Get请求(json参数)
1.引入httpclient 依赖

   <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.6</version>
    </dependency>

2.定义一个HttpGet实体类

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import java.net.URI;
/**

  • @author xf

  • @version 1.0.0

  • @ClassName HttpGetWithEntity

  • @Description TODO 定义一个带body的GET请求 继承 HttpEntityEnclosingRequestBase

  • @createTime 2020.11.18 13:51
    */
    public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
    private final static String METHOD_NAME = “GET”;

    @Override
    public String getMethod() {
    return METHOD_NAME;
    }
    public HttpGetWithEntity() {
    super();
    }
    public HttpGetWithEntity(final URI uri) {
    super();
    setURI(uri);
    }
    HttpGetWithEntity(final String uri) {
    super();
    setURI(URI.create(uri));
    }

}

3.HttpGet请求公共方法

/**
 * 发送get请求,参数为json
 * @param url
 * @param param
 * @param encoding
 * @return
 * @throws Exception
 */
public static String sendJsonByGetReq(String url, String param, String encoding) throws Exception {
    String body = "";
    //创建httpclient对象
    CloseableHttpClient client = HttpClients.createDefault();
    HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
    HttpEntity httpEntity = new StringEntity(param, ContentType.APPLICATION_JSON);
    httpGetWithEntity.setEntity(httpEntity);
    //执行请求操作,并拿到结果(同步阻塞)
    CloseableHttpResponse response = client.execute(httpGetWithEntity);
    //获取结果实体
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        //按指定编码转换结果实体为String类型
        body = EntityUtils.toString(entity, encoding);
    }
    //释放链接
    response.close();
    return body;
}

4.运行服务,本地测试调用一下该接口

/**
 * 测试 Get 请求
 */
@Test
public void test(){
    String url = "http://127.0.0.1:8012/export/getByBodyJson";
    Map<String, Object> map = new HashMap<>();
    map.put("stuName","张一山");
    map.put("school","北京戏剧学院");
    String reqParams = JSONArray.toJSON(map).toString();
    try {
        String s = sendJsonByGetReq(url, reqParams, "UTF-8");
        System.out.println("请求Get请求返回结果:"+s);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

三.使用HttpGet请求发送body入参调用成功

尽管这样解决了get 加body 体传参,但是仍建议大家使用post 加body!
————————————————
版权声明:本文为CSDN博主「余生一个帆」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44146379/article/details/109809386

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐