java Apache HttpClient 4.0-beta2 httppost,如何添加referer?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1150615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 15:22:28  来源:igfitidea点击:

Apache HttpClient 4.0-beta2 httppost, how to add a referer?

javahttpclient

提问by Lasoldo Solsifa

I'm trying to add a referer to an http post in Apache HttpClient (httpclient-4.0-beta2).

我正在尝试向 Apache HttpClient (httpclient-4.0-beta2) 中的 http 帖子添加引用。

I found some sample code that does this. The code works, but I'm wondering if there is not a simpler, more straightforward way to add the referer than using the (ominously named) addRequestInterceptor, which appears to take an (yikes!) inner class as a parameter.

我找到了一些执行此操作的示例代码。代码有效,但我想知道是否没有比使用(不祥的名称)addRequestInterceptor 更简单、更直接的方法来添加引用,它似乎采用(哎呀!)内部类作为参数。

The code in question begins below with "// add the referer header". I'm a novice, and this code is doing several things that I don't understand. Is this really the simplest way to add a referer to my http post?

有问题的代码以“// 添加引用标头”开头。我是新手,这段代码做了几件我不明白的事情。这真的是向我的 http 帖子添加引用的最简单方法吗?

Thanks for any pointers.

感谢您的指点。

// initialize request parameters
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("firstName", "John"));
formparams.add(new BasicNameValuePair("lastName", "Doe"));

// set up httppost
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost(submitUrl);
httppost.setEntity(entity);

// create httpclient
DefaultHttpClient httpclient = new DefaultHttpClient();

// add the referer header, is an inner class used here?
httpclient.addRequestInterceptor(new HttpRequestInterceptor()
{   
    public void process(final HttpRequest request, 
                        final HttpContext context) throws HttpException, IOException
    {
        request.addHeader("Referer", referer);
    }
});

// execute the request
HttpResponse response = httpclient.execute(httppost);

回答by Jon Skeet

Any reason not to do:

任何不这样做的理由:

httppost.addHeader("Referer", referer);

? HttpPostsubclasses (indirectly) AbstractHttpMessageso you should be able to just add headers that way.

? HttpPost子类(间接),AbstractHttpMessage因此您应该能够以这种方式添加标题。