EFOE EFOE - 1 month ago 36
reST (reStructuredText) Question

Error using httpclient on vertx

Hello i'm trying to perform a rest call on a distant ressources using the code bellow. on vertx 3.3.3 it works with defaulthttpclient (appache) but it's not asynchron

i still get the error:
nov. 01, 2016 8:15:08 AM io.vertx.core.http.impl.HttpClientRequestImpl
GRAVE: java.net.ConnectException: Connection refused: localhost/127.0.0.1:80

final HttpClient httpClient = vertx.createHttpClient();

final HttpGet getRequest = new HttpGet(uri);

httpClient.request(apiMethod.getHttpMethod(), uri, resultHandler -> {
resultHandler.statusCode();
if (resultHandler.statusCode() == 200) {
environment.setStatus(ApiStatus.OK);
apiMethod.setStatus(ApiStatus.OK);
} else {
environment.setStatus(ApiStatus.ERROR);
apiMethod.setStatus(ApiStatus.ERROR);
}
resultHandler.bodyHandler(buffer -> {
String message = "";
logger.debug("Output from Server .... \n");
logger.debug(buffer);
message = buffer.toString();
apiMethod.setCallingDate(new Date());
apiMethod.setCallingResult(message);
});
}).putHeader("content-type", "application/json").end();


Can anyone help?

Best regards,

Answer

It seems you're forgetting to configure the client to which host and port to connect to and it is using the default values localhost:80 as you can read from the exception.

You should be doing something like:

httpClient.request(GET, "www.yourserver.com", 80, uri, res -> {
  ...
});

Note that uri is not an URL so it should be something like:

/api/users?from=5&to=10

If you're looking for a more compact version then what you should be using is the requestAbs method:

httpClient
  .requestAbs(GET, "http://www.yourserver.com/api/users?from=5&to=10", res -> {
    ...
  });