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