我正在尝试向 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/