简体   繁体   English

如何发送带有正文的HTTP GET?

[英]How do I send an HTTP GET with a body?

Boss wants us to send a HTTP GET with parameters in the body. Boss希望我们发送一个在正文中带有参数的HTTP GET。 I can't figure out how to do this using org.apache.commons.httpclient.methods.GetMethod or java.net.HttpURLConnection;. 我不知道如何使用org.apache.commons.httpclient.methods.GetMethod或java.net.HttpURLConnection;来做到这一点。

GetMethod doesn't seem to take any parameters, and I'm not sure how to use HttpURLConnection for this. GetMethod似乎没有任何参数,而且我不确定如何为此使用HttpURLConnection。

HTTP GET method should NEVER have a body section. HTTP GET方法永远不应具有正文部分。 You can pass your parameters using URL query string or HTTP headers. 您可以使用URL查询字符串或HTTP标头传递参数。

If you want to have a BODY section. 如果要有一个BODY部分。 Use POST or other methods. 使用POST或其他方法。

You can extends the HttpEntityEnclosingRequestBase class to override the inherited org.apache.http.client.methods.HttpRequestBase.getMethod() but by fact HTTP GET does not support body request and maybe you will experience trouble with some HTTP servers, use at your own risk :) 您可以扩展HttpEntityEnclosingRequestBase类以覆盖继承的org.apache.http.client.methods.HttpRequestBase.getMethod(),但实际上HTTP GET不支持主体请求,也许您会遇到一些HTTP服务器的麻烦,请自行使用风险:)

public class MyHttpGetWithEntity extends HttpEntityEnclosingRequestBase { public final static String GET_METHOD = "GET"; 公共类MyHttpGetWithEntity扩展了HttpEntityEnclosingRequestBase {public final static String GET_METHOD =“ GET”;

public MyHttpGetWithEntity(final URI uri) {
    super();
    setURI(uri);
}

public MyHttpGetWithEntity(final String uri) {
    super();
    setURI(URI.create(uri));
}

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

} }

then 然后

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class HttpEntityGet {

    public static void main(String[] args) {

        try {
            HttpClient client = new DefaultHttpClient();
            MyHttpGetWithEntity e = new MyHttpGetWithEntity("http://....");
            e.setEntity(new StringEntity("mystringentity"));
            HttpResponse response = client.execute(e);
            System.out.println(IOUtils.toString(response.getEntity().getContent()));
        } catch (Exception e) {
            System.err.println(e);
        }
    }
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM