我正在尝试将引用添加到Apache HttpClient(httpclient-4.0-beta2)中的http帖子。
我发现了一些示例代码。代码可以工作,但我想知道是否有一个更简单,更直接的方式来添加引用,而不是使用(不祥的命名)addRequestInterceptor,它似乎将(yikes!)内部类作为参数。
有问题的代码从下面开始“//添加referer标题”。我是新手,这段代码正在做一些我不理解的事情。这真的是将引用添加到我的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);
答案 0 :(得分:16)
任何不做的理由:
httppost.addHeader("Referer", referer);
? HttpPost
子类(间接)AbstractHttpMessage
因此您应该能够以这种方式添加标题。