Hadi Hoteit
Hadi Hoteit

Reputation: 120

HTTP POST Request with Json body giving error code 400

I'm trying to send a Json format in body of POST request in java.

I tried a lot of codes from the internet and StackOverflow, but nothing is working.

I keep getting java.io.IOException: Server returned HTTP response code: 400 for URL: http://localhost:8080/engine-rest/message.

After trying a lot on Postman i noticed it only accepts Json format body, i tried using json libraries like Gson, yet still nothing worked.

Any ideas on how to fix my code? Again I did try to copy a lot of codes from the internet so please don't send me a similar title stackoverflow thread and call the question repetitive.

Thank you in advance.

public class PostRequest {

    FileWriter myWriter;
    URL url;
    public void sendPost(String Url) throws IOException {
        
        String name = "{\"messageName\": \"URLFound\", \"businessKey\": \"3\"}";
        
        try {
            myWriter = new FileWriter("C:\\Users\\test\\Desktop\\camunda test save\\Post.txt");
            url = new URL ("http://localhost:8080/engine-rest" + Url);
            HttpURLConnection http = (HttpURLConnection)url.openConnection();
            
            http.setRequestMethod("POST");
            http.setDoOutput(true);
            http.setRequestProperty("Content-Type", "application/json");
            
            OutputStream os = http.getOutputStream();
            byte[] input = name.getBytes("utf-8");
            os.write(input, 0, input.length);
            
            BufferedReader in = new BufferedReader(new InputStreamReader(http.getInputStream()));
            StringBuffer response = new StringBuffer();
            while ((in.ready())) {
                response.append(in.readLine());
            }
            in.close();
            
            //Writing result on .txt
            myWriter.append(response.toString() + "\n" +url);

        }
        catch(Exception e){
            myWriter.append(e.toString());
        }
        myWriter.close();
        
        
    }
}

Upvotes: 0

Views: 945

Answers (2)

dkrx81
dkrx81

Reputation: 63

Java cant create an object from your json. Check if all fields are sent in the request body of the java class that is expected on the backend side.

Upvotes: 0

Related Questions