Issue
I have got a basic curl like below:
curl -X POST \
'https://aogt.pl/auth/' \
-H 'Authorization: Basic NGZjMjExNWQyYTZk' \
-H 'Content-Type: application/x-www-form-urlencoded' \
-d 'client_id=4fc2115'
When I run it in the console on e.g. Ubuntu everything work correctly, I get a good response. Now I would like to map this curl into the java code using okhttp. I write below code:
public class TestMain {
private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static void main(String[] args) throws IOException {
String data = "client_id=4fc2115";
RequestBody body = RequestBody.create(JSON, data);
Request request = new Request.Builder()
.url("https://aogt.pl/auth/")
.addHeader("Authorization", "Basic NGZjMjExNWQyYTZk")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
.post(body)
.build();
OkHttpClient client = new OkHttpClient();
Response response = client.newCall(request).execute();
System.out.println(response.body().string());
}
}
The pom file look like:
<dependencies>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.2.0</version>
</dependency>
</dependencies>
The problem is that when I run this code I get "400 Bad Request" so this is problem with server. I wrong map above curl into the java code into the http. Probably the problem is in POST body, because it is not JSON, but what I need to change here, could you please tell me what is wrong? Thank you very much.
Solution
The request you want to send has content-type as "application/x-www-form-urlencoded". So creating the body as a JSON would not work. You should try forming body in following way:
RequestBody body = new FormBody.Builder().add("client_id", "id_value").build();
Answered By - ankit jain Answer Checked By - David Marino (WPSolving Volunteer)