带有正文的 Apache HttpClient GET [英] Apache HttpClient GET with body

查看:30
本文介绍了带有正文的 Apache HttpClient GET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发送一个包含 json 对象的 HTTP GET.有没有办法设置 HttpClient HttpGet 的主体?我正在寻找等效的 HttpPost#setEntity.

解决方案

据我所知,使用 Apache 库附带的默认 HttpGet 类无法做到这一点.但是,您可以子类化 HttpEntityEnclosureRequestBase 实体并将方法设置为 GET.我尚未对此进行测试,但我认为以下示例可能是您要查找的内容:

import org.apache.http.client.methods.HttpEntityEnclosureRequestBase;公共类 HttpGetWithEntity 扩展了 HttpEntityEnclosureRequestBase {公共最终静态字符串 METHOD_NAME = "GET";@覆盖公共字符串 getMethod() {返回 METHOD_NAME;}}

然后您可以执行以下操作:

<预><代码>...HttpGetWithEntity e = new HttpGetWithEntity();...e.setEntity(yourEntity);...响应 = httpclient.execute(e);

I am trying to send an HTTP GET with a json object in its body. Is there a way to set the body of an HttpClient HttpGet? I am looking for the equivalent of HttpPost#setEntity.

解决方案

From what I know, you can't do this with the default HttpGet class that comes with the Apache library. However, you can subclass the HttpEntityEnclosingRequestBase entity and set the method to GET. I haven't tested this, but I think the following example might be what you're looking for:

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

public class HttpGetWithEntity extends HttpEntityEnclosingRequestBase {
    public final static String METHOD_NAME = "GET";

    @Override
    public String getMethod() {
        return METHOD_NAME;
    }
}

Edit:

You could then do the following:

...
HttpGetWithEntity e = new HttpGetWithEntity();
...
e.setEntity(yourEntity);
...
response = httpclient.execute(e);

这篇关于带有正文的 Apache HttpClient GET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆