Java HttpAsyncPost设置标题
我目前正在使用Apache的HttpComponents,包括HttpAsyncClient测试版,但我想知道。如何设置HttpAsyncPost的标题 我目前有:Java HttpAsyncPost设置标题,java,asynchronous,httpclient,Java,Asynchronous,Httpclient,我目前正在使用Apache的HttpComponents,包括HttpAsyncClient测试版,但我想知道。如何设置HttpAsyncPost的标题 我目前有: HttpAsyncPost asyncRequest = new HttpAsyncPost(channel, "id=15846"); 但是如何设置此请求的头?如果您不介意升级到最新快照,可以使用httpasynchmethods\create方法从任意HttpUriRequest实例创建httpasynchrequestpro
HttpAsyncPost asyncRequest = new HttpAsyncPost(channel, "id=15846");
但是如何设置此请求的头?如果您不介意升级到最新快照,可以使用
httpasynchmethods\create
方法从任意HttpUriRequest
实例创建httpasynchrequestproducer
或者,您可以重写HttpAsyncPost#createRequest()
方法,并向超类返回的HttpEntityEnclosingRequest
实例添加自定义头
希望这有帮助。我的第一个解决方案是使用cast to
BasicAsyncRequestProducer
。我不能依赖方法generateRequest()
,它基本上是getter,但它在将来会改变,正如方法的名称所示。所以我坚持回答
根据答案使用我自己的createPost
方法:
BasicAsyncRequestProducer request = (BasicAsyncRequestProducer) HttpAsyncMethods.createPost("http://some/uri", "some payload", ContentType.DEFAULT_TEXT);
request.generateRequest().setHeader("header name", "header value");
createPost("http://some/uri", "some payload", ContentType.DEFAULT_TEXT, new BasicHeader("header name", "header value"));
static class RequestProducerImpl extends BasicAsyncRequestProducer {
protected RequestProducerImpl(
final HttpHost target,
final HttpEntityEnclosingRequest request,
final HttpAsyncContentProducer producer) {
super(target, request, producer);
}
}
public static HttpAsyncRequestProducer createPost(
final String requestURI,
final String content,
final ContentType contentType, Header... headers) throws UnsupportedEncodingException {
final HttpPost httppost = new HttpPost(requestURI);
final NStringEntity entity = new NStringEntity(content, contentType);
httppost.setEntity(entity);
httppost.setHeaders(headers);
final HttpHost target = URIUtils.extractHost(URI.create(requestURI));
return new RequestProducerImpl(target, httppost, entity);
}