How to POST json as request body with Jetty http client?
11,190
I was able to figure it out myself. The solution was staring at me the whole time.
Added one line and everything worked:
// Set request body
request.content(new StringContentProvider(JSON_HERE), "application/json");
Hope it will be helpful to others as well.
Author by
lkallas
Updated on June 04, 2022Comments
-
lkallas about 2 years
I'm stuck with adding JSON to POST request body. There just isn't any method that sets the body of the request.
Is there any way I can achieve this. Otherwise I have to drop using Jetty.
This is how I make my POST request:
Request request = httpClient.POST(url); //request.method(HttpMethod.POST); request.header(HttpHeader.ACCEPT, "application/json"); request.header(HttpHeader.CONTENT_TYPE, "application/json"); // Add basic auth header if credentials provided if (isCredsAvailable()) { String authString = username + ":" + password; byte[] authEncBytes = Base64.getEncoder().encode(authString.getBytes()); String authStringEnc = "Basic " + new String(authEncBytes); request.header(HttpHeader.AUTHORIZATION, authStringEnc); } request(send);
Any help is appreciated!
-
Vince Bowdren almost 8 yearsHi 许宗晖, and welcome to Stack Overflow. As well as the code, your answer needs some context; for example, can you explain how and why it solves the questioner's problem? That will make it more useful to them, and also more useful to other readers of the site who are looking for answers to similar problems.