如何在NIO异步调用上设置HTTP post参数?

时间:2014-03-11 09:18:03

标签: java http post asynchronous nio

答案必须非常简单,但我仍然无法找到它。让我们说我有一个使用GET参数的Java异步调用的实例:

final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
URL url = new URL("http://www.myurl.com?param1=blabla");

try {
    final Future<Boolean> future = client.execute(
        HttpAsyncMethods.createGet(url), 
        new MyResponseConsumer(), 
        null
    );
    NotifierThread hilo = new NotifierThread(future);
    hilo.start();
} finally {
    client.close();
}

但是如果我想为&#34; param1&#34;使用POST参数怎么办?而不是GET?我怎么能实现这个目标?我无法在HttpAsyncMethods库上找到任何方法来执行此操作。

任何帮助都将不胜感激。

此致

1 个答案:

答案 0 :(得分:1)

好吧,我终于知道如何执行此操作并在此处发布,以防其他人有同样的疑问(正如我怀疑答案并不那么困难:-)):

final CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
client.start();
URL url = new URL("http://www.myurl.com");

StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> param:params.entrySet()) {
    sb.append(param.getKey()+"="+param.getValue()+"&");
}

if (sb.length() > 0) {
    sb = new StringBuilder(sb.substring(0, sb.length()-1));
}

try {
    HttpAsyncRequestProducer prod = HttpAsyncMethods.createPost(
        BASE_URL+call, 
        sb.toString(), 
        ContentType.APPLICATION_FORM_URLENCODED
    );
    final Future<Boolean> future = client.execute(
        prod, 
        new MyResponseConsumer(),
        null
    );
    NotifierThread hilo = new NotifierThread(future);
    hilo.start();
} finally {
    client.close();
}

此致