Apache HttpClient 4.0-beta2 httppost,如何添加引用?

2022-09-04 02:56:13

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

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

有问题的代码在下面以“//添加引用标头”开头。我是一个新手,这段代码正在做一些我不明白的事情。这真的是向我的http帖子添加引用者的最简单方法吗?

感谢您的指点。

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

答案 1

任何理由不这样做:

httppost.addHeader("Referer", referer);

? 子类(间接),所以你应该能够以这种方式添加标头。HttpPostAbstractHttpMessage


答案 2

推荐