我正在尝试在Apache HttpClient(httpclient-4.0-beta2)中添加一个referer到http post请求中。
我找到了一些示例代码来实现这个目的,此代码是可行的。但是我想知道是否有比使用(名称令人生畏的)addRequestInterceptor更简单、更直接的方法来添加referer,因为它似乎需要将一个(呀!)内部类作为参数。
下面的代码从"// add the referer header"开始,我是初学者,对于代码中的许多操作都感到困惑。请问这是添加referer到我的http post的最简单方法吗?
谢谢任何指点。
// 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);