Java发送Http请求之——发送请求参数在Body中Get请求

1.背景要求

发送Get请求,但是请求参数要放在请求body内,所以经过多方查证后整理出来以下代码。

2.POM依赖

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.2</version>
        </dependency>

        <dependency>
            <groupId>commons-lang</groupId>
            <artifactId>commons-lang</artifactId>
            <version>2.6</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>

3.发送Get请求工具类

package com.example.demo.util;

import com.example.demo.entity.ReqParamEntity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

    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;
    }

    public static void main(String[] args) {
        String url = "http://localhost:8080/receiveGetReq";

        Gson gson = new GsonBuilder().create();

        ReqParamEntity reqParamEntity = new ReqParamEntity();

        reqParamEntity.setUserName("请求参数在请求body中");
        reqParamEntity.setPassWord("发送Get请求");

        String reqParams = gson.toJson(reqParamEntity);

        try {
            String result1 = sendJsonByGetReq (url, reqParams, "utf-8");
            System.out.println (result1);

        } catch (Exception e) {
            e.printStackTrace ( );
        }
    }

}

4.工具类关联类

package com.example.demo.util;

import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;

import java.net.URI;

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));
    }

}

5.验证是否请求成功

package com.example.demo.controller;

import com.example.demo.entity.ReqParamEntity;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.web.bind.annotation.*;

@RestController
public class DemoController {

    @GetMapping("/receiveGetReq")
    public String receiveGetReq(@RequestBody ReqParamEntity reqParamEntity){

        Gson gson = new GsonBuilder().create();
        System.out.println("reqParamEntity="+gson.toJson(reqParamEntity));
        return "请求成功";
    }

}

6.总结

请求成功

  • 12
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
HTTP/1.1规范GET请求是不支持请求体(request body)的,只有POST请求及其它一些请求方式支持。但是在实际,有时候需要在发送GET请求时带上一些参数,这些参数需要通过请求体来传递,这种情况下可以采用以下两种方式实现: 1. 利用HTTP Post来模拟HTTP Get带body 代码示例: ```java URL url = new URL("http://example.com/resource"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write("param1=value1&param2=value2"); writer.flush(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); } writer.close(); reader.close(); ``` 2. 采用HTTP Get方式,但在请求URL带上参数 代码示例: ```java String url = "http://example.com/resource?param1=value1&param2=value2"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println(response.toString()); ``` 需要注意的是,第二种方式虽然可以在请求传递参数,但是可能会被一些HTTP代理服务器或者Web服务器认为是不符合规范的请求,因此并不是所有的Web服务器都支持此方式。建议采用第一种方式来发送请求体的请求

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值