Reputation: 16663
I am currenty using Apache's HttpComponents including the HttpAsyncClient beta, but I was wondering. How do I set the headers for a HttpAsyncPost?
I currently have:
HttpAsyncPost asyncRequest = new HttpAsyncPost(channel, "id=15846");
But how do I set the headers for this request?
Upvotes: 2
Views: 832
Reputation: 781
My first solution using cast to BasicAsyncRequestProducer
. I can't rely on method generateRequest()
which is basically getter but it would change in the future as name of the method suggests. So I sticked to @oleg answer.
BasicAsyncRequestProducer request = (BasicAsyncRequestProducer) HttpAsyncMethods.createPost("http://some/uri", "some payload", ContentType.DEFAULT_TEXT);
request.generateRequest().setHeader("header name", "header value");
Using my own createPost
method based on @oleg answer:
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);
}
Upvotes: 0
Reputation: 27613
You could use HttpAsyncMethods#create
method in order to create an HttpAsyncRequestProducer
from an arbitrary HttpUriRequest
instance, if you do not mind upgrading to the latest snapshot.
Alternatively, you can override HttpAsyncPost#createRequest()
method and add custom headers to the HttpEntityEnclosingRequest
instance returned by the super class.
Hope this helps.
Upvotes: 3