Home > Software design >  How to solve KeyError: 400 Bad Request
How to solve KeyError: 400 Bad Request

Time:05-18

I have a server to which I want to send post requests in the form of json in Java. But after sending, it gives the answer: "KeyError: 400 Bad Request: The browser (or proxy) send a request that this server could not understand.". No matter how I change the data, it still gives this error, and the sent requests do not appear on the server. How can I fix this?

    URL url = new URL("http://buldakovn.pythonanywhere.com/addStudent");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/json; utf-8");
    connection.setRequestProperty("Accept", "application/json");
    connection.setDoOutput(true);

    //request body
    String str1 = "{FName: "   name   ", LName: "   surname   ", VkId: "   vk   ", TelegrammId: "   telegram   ", Group: "   group "}";

    OutputStream out = connection.getOutputStream();
    byte [] input = str1.getBytes(StandardCharsets.UTF_8);
    out.write(input, 0, input.length);
    out.close();

CodePudding user response:

This first thing that you need to do is look at the endpoint that you're POSTing to and determine what it accepts. By this I mean, are you certain that it takes json? Are you certain that your payload is correct?

There's really no way around it, to consume an API you need to know what it expects.

Secondly, your String str1 does not contain valid JSON, so even if you had all the fields and types correct, this isn't going to work.

Valid Json would read as

{"FName": "someName", "LName": "someName"}

What you have there produces this

{FName: someName, LName: someName}

Notice the lack of quotations in your string? Even the StackOverflow parser doesn't know what to make of this :)

  • Related