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

标签 java httpclient

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

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

有问题的代码在下面以“//add the referer header”开头。我是新手,这段代码做了几件我不明白的事情。这真的是向我的 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);

最佳答案

任何不这样做的理由:

httppost.addHeader("Referer", referer);

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

关于java - Apache HttpClient 4.0-beta2 httppost,如何添加引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1150615/

相关文章:

java - 如何将mysql查询转换为jpa命名查询

java - java/.Net 必需的 "code toolset"

java - 如何使用准备好的语句设置当前日期和时间?

java - 在jsp和java之间重用变量名(Spring)

java - Android 中的双击缩放

c# - 使用 HttpClient 时如何在 HttpContent 中设置大字符串?

android - 有什么方法可以使用 HttpUrlConnection 正确获取上传进度

android - 如何异步执行 httprequest 并显示下载响应的进度

java - 使用网络客户端发布数据

java - HttpClient 身份验证,保持登录状态