HttpGet请求传body参数

文章介绍了在遇到一个Get请求但参数在Body中的场景时,如何使用Java的HttpClinet库自定义HttpGetWithEntity类来实现这种非标准的调用,并提供了具体的代码示例。虽然这种方式可以实现,但作者建议通常应使用POST请求来传递Body参数。

前言

最近调用公司项目一个接口时,发现该接口是一个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!

转:我是如何实现HttpGet请求传body参数的!-爱代码爱编程

### 如何在 HTTP POST 请求Body 参数 #### 使用 PHP 进行 HTTP POST 请求Body 参数 当使用 PHP 发送 HTTP POST 请求时,可以通过 `cURL` 库来构建请求并将数据作为 body 的一部分发送。下面展示了一个完整的例子: ```php <?php // 要发送的数据数组 $data = array( 'name' => 'John Doe', 'email' => 'johndoe@example.com' ); // 初始化 cURL 会话 $ch = curl_init('https://example.com/api/endpoint'); // 设置必要的选项 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data)); // 执行请求并捕获响应 $response = curl_exec($ch); // 关闭 cURL 会话 curl_close($ch); echo $response; ?> ``` 此代码片段展示了如何创建一个新的 cURL 会话,并配置它以执行带有表单编码参数的 POST 请求[^1]。 #### Java 中利用 HttpClient 发送带 Body 的 POST 请求 对于 Java 开发者来说,可以借助 Apache HttpClient 或 JDK 自带的 `HttpURLConnection` 来完成同样的任务。以下是基于 Apache HttpClient 实现的一个实例: ```java import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; public class PostExample { public static void main(String[] args) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpPost postRequest = new HttpPost("https://example.com/api/endpoint"); // JSON 格式的 payload 数据 String jsonPayload = "{\"name\":\"Jane\",\"email\":\"janedoe@example.com\"}"; // 将字符串转换成实体对象附加到请求上 StringEntity entity = new StringEntity(jsonPayload,"UTF-8"); postRequest.setEntity(entity); postRequest.setHeader("Content-Type", "application/json"); try (CloseableHttpResponse response = httpClient.execute(postRequest)) { System.out.println(response.getStatusLine().getStatusCode()); } } } } ``` 这段程序说明了怎样构造一个包含 JSON 文本内容类型的 POST 请求体,并指定了目标 URL 和实际要送的内容[^4]。 #### Spring Cloud OpenFeign 定义接口接收 POST 请求及其 Body 参数 如果是在微服务架构下工作,则可能更倾向于采用声明式 RESTful Web Service Client —— Feign。定义好接口之后,在控制器方法里可以直接接受封装好的 POJO 对象作为入参: ```java @RestController @RequestMapping("/api") public class MyController { @PostMapping(value="/submit", consumes="application/json") public ResponseEntity<String> submit(@RequestBody User user){ return ResponseEntity.ok("Received name: "+user.getName()+", email:"+user.getEmail()); } } class User{ private String name; private String email; // Getters and Setters... } ``` 上述代码段表明了如何设计 API 接口以便能够处理来自客户端提交过来的 JSON 形式的用户信息[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值