Reputation: 11
I am struggling to get an Post Request to return a 200 answer in my project. We have a Postman test, that is working fine and generates the following code:
OkHttpClient client = new OkHttpClient().newBuilder()
.build();
MediaType mediaType = MediaType.parse("text/plain");
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("customerNumber","1000000")
.addFormDataPart("username","razisami")
.addFormDataPart("password","razisami1234")
.build();
Request request = new Request.Builder()
.url("http://localhost:8085/ImageGateway/login")
.method("POST", body)
.build();
Response response = client.newCall(request).execute();
'''
I need the same code written again to work with Apache HttpClient, see [Posting with HttpClient][1]
[1]: https://www.baeldung.com/httpclient-post-http-request
Upvotes: 1
Views: 1510
Reputation: 27538
This is the equivalent code with Apache HttpClient 5.1, which I recommend to be used instead of HttpClient 4.5 for new projects
CloseableHttpClient httpclient = HttpClients.createSystem();
ClassicHttpRequest request = ClassicRequestBuilder.post()
.setUri(new URI("http://localhost:8085/ImageGateway/login"))
.addParameter("customerNumber","1000000")
.addParameter("username","razisami")
.addParameter("password","razisami1234")
.build();
httpclient.execute(request, response -> {
// do something useful with the response
return null;
});
Upvotes: 2