Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Ragesh Kanagaraj
Ragesh Kanagaraj
3,637 Points

Failed : HTTP error code : 400 While postin JSON data to URL

I tried searching the net for this issue but finally ended up getting no proper answer.

I am trying to post a json data to a URL, I have no idea where my code went wrong, I am getting Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 400 It would be of great help if anyone could help me outwith this issue.

MY CODE :

public class JsonTest {

public static void main(String[] args) throws IOException {
    try {

        URL url = new URL("http://10.48.151.32:30304/transactionManagement/v2/transaction");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");

        String input = "{\"qty\":100,\"name\":\"iPad 4\"}";

        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();

        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }

        conn.disconnect();

      } catch (MalformedURLException e) {

        e.printStackTrace();

      } catch (IOException e) {

        e.printStackTrace();

     }

    }

}

My Error Exception : Exception in thread "main" java.lang.RuntimeException: Failed : HTTP error code : 400 at JsonTest.main(JsonTest.java:36)