Question

the answer to this must be pretty simple, but I'm still unable to find it. Let's say that I have a working example of Java Asynchronous call that makes use of GET parameters:

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();
}

but what if I want to use POST parameters for "param1" instead of GET?. How can I achieve this?. I was unable to find any method on the HttpAsyncMethods library to do this.

Any help would be appreciated.

Regards

Était-ce utile?

La solution

Well, I finally found out how this could be performed and I'm posting it here in case someone else has the same doubt (just as I suspected the answer was not so difficult :-) ):

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();
}

Regards

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top