3

I'm trying to make a POST request with custom headers and json as string on body

Here's my code

HttpRequest request2 = HttpRequest.newBuilder()
                .uri(URI.create(POSTS_API_URL))
                .headers("accept", "text/plain; charset=UTF-8", "XF-Api-Key", "MYAPIKEY")
                .POST(HttpRequest.BodyPublishers.ofString(json))

                .build();

        System.out.println(request2); //result : https://******.fr/api/auth/ POST
        System.out.println(request2.headers()); //result : java.net.http.HttpHeaders@8e33ff08 { {accept=[text/plain; charset=UTF-8], XF-Api-Key=[MYAPIKEY]} }

        HttpResponse<String> response2 = client.send(request2, HttpResponse.BodyHandlers.ofString());

        // print status code
        System.out.println(response2.statusCode()); //400
        // print json code
        System.out.println(json); //{"login":"LunaLune","password":"***********"}
        // print response body
        System.out.println(response2.body()); //mandatory input missing : login, password

And my json String

 String json = "{" +
                "\"login\":\"LunaLune\"," +
                "\"password\":\"*********\"" +
                "}";

But when I print the request I get : https://*******.fr/api/auth/ POST

the POST request is empty

I googled many forums, code examples ect... but I see that my code where correct according many examples I seen.

So if someone know what is my problem ? Thanks in advance !

2 Answers2

0

You need to set "Content-Type" as "application/json" in the request header.

See: Which JSON content type do I use?

soKira
  • 71
  • 1
  • 2
0

I had the same problem. I solved by adding an header with Content-Type set to application/x-www-form-urlencoded and by writing the credentials URL encoded.

HttpRequest request = HttpRequest.newBuilder()
        .uri(URI.create("https://example.com/post.php"))
        .header("Content-Type", "application/x-www-form-urlencoded")
        .POST(BodyPublishers.ofString("password=password&email=someone@example.com"))
        .build();
Birio
  • 35
  • 1
  • 5