HttpAsyncPost设置标头

时间:2011-07-18 13:04:56

标签: java asynchronous httpclient

我目前正在使用Apache的HttpComponents,包括HttpAsyncClient beta,但我很想知道。如何设置HttpAsyncPost的标头?

我目前有:

HttpAsyncPost asyncRequest = new HttpAsyncPost(channel, "id=15846");

但是如何设置此请求的标头?

2 个答案:

答案 0 :(得分:3)

如果您不介意升级到最新的快照,可以使用HttpAsyncMethods#create方法从任意HttpAsyncRequestProducer实例创建HttpUriRequest

或者,您可以覆盖HttpAsyncPost#createRequest()方法并将自定义标头添加到超类返回的HttpEntityEnclosingRequest实例中。

希望这有帮助。

答案 1 :(得分:0)

我的第一个使用强制转换为generateRequest()的解决方案。我不能依赖方法BasicAsyncRequestProducer request = (BasicAsyncRequestProducer) HttpAsyncMethods.createPost("http://some/uri", "some payload", ContentType.DEFAULT_TEXT); request.generateRequest().setHeader("header name", "header value"); ,它基本上是吸气剂,但是随着方法名称的提示,它将来会改变。所以我坚持@oleg回答。

createPost

使用我自己的基于@oleg答案的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); } 方法:

# split time spans into their different time elements
l <- strsplit(x, ":")

# pad vector with leading zeros. Here 4 is the maximum number of time elements
m <- sapply(l, function(x) as.numeric(c(rep(0, 4 - length(x)), x)))

# convert result to desired unit, e.g. seconds
m[1 , ] * 24*60*60 + m[2 , ] * 60*60 + m[3 , ] * 60 + m[4 , ]
# [1]     28.6575     74.0920   3938.1230 518378.7211