GET
, POST
, PUT
and DELETE
are supported:
http.get()
http.post()
http.put()
http.delete()
http.trace()
http.patch()
http.options()
http.get().url("http://pizza-delivery.org/margheritas").execute();
If you want to make a number of requests to a given service, you can specify the baseUrl
constructor parameter:
var http = new HttpClient("http://water-melon.com");
http.get().path("/slice").execute();
You can either specify a query in url
or path
, or via query
parameter:
http.put().path("/put?some=query&some=more")
http.put().path("/put").query("some", "query").query("some", "more")
NB! if
url
orpath
contains a query already,query
parameter is ignored.
http.put()
.path("/put")
.header("Accept", "application/json")
.header("Content-Type", "application/json")
.execute();
Default headers are sent with each request. It is also possible to override default headers per request:
var http = new HttpClient("http://water-melon.com", [
Accept: 'application/json',
'Content-Type': 'application/json'])
http.put()
.path("/put")
.header("Content-Type", "application/json")
.execute();
Any non-string body is serialized as JSON.
String
:
http.delete()
.path("/delete")
.body("<xml></xml>")
.execute();
Map
:
http.put()
.path("/put")
.body(Map.of("key", "value"))
.execute()
If an instance of java.io.File
is provided as body
argument, it will be wrapped into a MultipartFile
:
http.put()
.path("/post")
.body(new File("/tmp/input.json"))
.execute();
var response = http.get().path("/get").execute();
assert response.statusCode() == ResponseCode.OK;
var response = http.get().path("/get").execute();
assert response.headers().equals(Map.of(
"Content-Type", List.of("application/json", "application/vnd.tomtom+json"),
"Connection", "keep-alive"));
By default, the response body is a String:
Response<String> response = http.get().path("/get").execute();
assert response.body().equals("A string");
A valid JSON response body can be deserialized into a Java object.
Response<Map> response = http.get().path("/get").expecting(Map.class).execute();
assert response.body().equals(Map.of("key", "value"));
Response<BananaIceCream> response = http.get()
.path("/ice-cream?banana=true")
.expecting(BananaIceCream.class);
assert response.body() instanceof BananaIceCream
Response<List<Map>> response = http.get().path("/get")
.expecting(List.class).of(Map.class);
assert response.body().equals(List.of(
Map.of("key", "value"),
Map.of("another-key", "another value")));