Calling an HTTP service

You can create a WebClient with a base URI and send a request with a relative path.

import com.linecorp.armeria.client.WebClient;
import com.linecorp.armeria.common.AggregatedHttpResponse;
import com.linecorp.armeria.common.HttpHeaderNames;
import com.linecorp.armeria.common.HttpMethod;
import com.linecorp.armeria.common.RequestHeaders;

WebClient webClient = WebClient.of("http://example.com/");

// Send a simple GET request.
AggregatedHttpResponse res1 = webClient.get("/foo/bar.txt").aggregate().join();

// Send a GET request with an additional header.
RequestHeaders getJson = RequestHeaders.of(HttpMethod.GET, "/foo/bar.json",
                                           HttpHeaderNames.ACCEPT, "application/json");

AggregatedHttpResponse res2 = webClient.execute(getJson).aggregate().join();

// Send a simple POST request encoded in UTF-8.
AggregatedHttpResponse res3 = webClient.post("/upload", "{ \"foo\": \"bar\" }")
                                       .aggregate().join();

You can also create a WebClient without a base URI and send a request with an absolute URI. The ad-hoc WebClient would be useful in the following cases:

  • Sending requests to arbitrary endpoints
  • Building a proxy server
  • Handling redirected requests
import com.linecorp.armeria.common.HttpStatus;
import com.linecorp.armeria.common.HttpHeaderNames;

// Create a WebClient without a base URI.
WebClient webClient = WebClient.of();

// Send a request with an absolute URI.
AggregatedHttpResponse res1 = webClient.get("http://example.com/foo/bar.txt")
                                       .aggregate()
                                       .join();

// Send a GET request with an authority header.
HttpRequest request = HttpRequest.of(RequestHeaders.builder()
                                                   .scheme(SessionProtocol.HTTP)
                                                   .authority("example.com")
                                                   .method(HttpMethod.GET)
                                                   .path("/foo/bar.txt")
                                                   .build());
AggregatedHttpResponse res2 = webClient.execute(request).aggregate().join();

// Handle a redirected request
AggregatedHttpResponse redirected = webClient.get("http://example.com/redirect")
                                             .aggregate()
                                             .join();
assert redirected.status() == HttpStatus.TEMPORARY_REDIRECT;
String location = redirected.headers().get(HttpHeaderNames.LOCATION);
AggregatedHttpResponse actual = webClient.get(location).aggregate().join();

See also