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


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.


public class JsonTest {

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

        URL url = new URL("");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Content-Type", "application/json");

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

        OutputStream os = conn.getOutputStream();

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

        BufferedReader br = new BufferedReader(new InputStreamReader(

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


      } catch (MalformedURLException e) {


      } catch (IOException e) {





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