使用HttpClient发送带body的GET请求

有时候我们会有一些奇怪的需求,比如使用带body的GET请求来请求数据,虽然HTTP协议里并没有禁止使用带body的GET请求,但是一般我们并不使用这种请求格式,而且HttpClient本身并没有定义带body的GET请求。此时怎么办呢?

我们可以自己定义一个带body的GET请求。首先,我们可以定义一个继承了 HttpEntityEnclosingRequestBase 的 HttpGetWithEntity 类,设置其请求方法为 GET:

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

然后,在调用时

HttpGetWithEntity oHttpGet = new HttpGetWithEntity(url);
HttpEntity httpEntity = new StringEntity(body, ContentType.APPLICATION_JSON);
oHttpGet.setEntity(httpEntity);

参考

https://stackoverflow.com/questions/12535016/apache-httpclient-get-with-body

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值