I am using the built in httpclient to issue a "get" query to an external service that needs authentication. More specifically, I am trying to submit queries to splunk from my service. How do I pass in the user credentials in the request? I want to use the basic auth instead of dealing with authentication tokens.
Vert. x Web Client is an asynchronous HTTP and HTTP/2 client. The Web Client makes easy to do HTTP request/response interactions with a web server, and provides advanced features like: Json body encoding / decoding. request/response pumping.
This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference. @FunctionalInterface public interface Handler<E> A generic event handler. This interface is used heavily throughout Vert. x as a handler for all types of asynchronous occurrences.
public interface Router extends Handler<HttpServerRequest> A router receives request from an HttpServer and routes it to the first matching Route that it contains. A router can contain many routes. Routers are also used for routing failures.
Basic auth is all about the Authorization Header.
You should add that header with a value composed of "basic " (note the blank) and your login:pass (separated by a colon) encoded in base64. This is only secure if you're using HTTPS.
Here is how I get this done in vert.x :
HttpClient client = vertx.createHttpClient().setSSL(true)
.setTrustAll(true) //You may not want to trust them all
.setHost("api.myawesomeapi.com")
.setPort(443);
HttpClientRequest clientRequest = client.get("/"+action+"/?"+params, new Handler<HttpClientResponse>() {
public void handle(final HttpClientResponse response) {
if (response.statusCode==200){
// It worked !
} else {
// Oops
}
}
});
clientRequest.putHeader(HttpHeaders.Names.AUTHORIZATION, "Basic "+base64key);
Here I already have the base64key, but if I had to create it, I would use something like :
base64key = Base64.encodeBytes(new StringBuilder(apiKey).append(":").append(secretKey).toString().getBytes(), Base64.DONT_BREAK_LINES);
If you use POST instead of get, don't forget to add the required headers :
clientRequest.putHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(params.getBytes().length))
.putHeader(HttpHeaders.Names.CONTENT_TYPE, "application/x-www-form-urlencoded")
.write(params);
I hope it helps
Hugo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With