1

I have created a Django Rest server. And I am trying to POST a JSON content in java using HttpURLConnection. However, when I am registering OutputStream in java, the server get a POST request with no JSON content. Hence the server rejecting the request with HTTP response code 400. I did write JSON data just after registering OutputSream. May be POST has been made before writing to OutputStream. The following is the code in JAVA.

    public static void post(HttpURLConnection urlConnection1)
        throws IOException, InterruptedException {
    // urlConnection.setRequestMethod("POST");

    URL url = new URL("http://127.0.0.1:8000/message/");
    byte[] authStr=Base64.encodeBase64("sp:password".getBytes());
    String enc=new String(authStr);

    HttpURLConnection urlConnection = (HttpURLConnection) url
            .openConnection();
    urlConnection.setRequestProperty("Authorization", "Basic "+ enc);
    try {

        urlConnection.setDoOutput(true);
        urlConnection.setChunkedStreamingMode(0);
        urlConnection
                .setRequestProperty("Content-Type", "application/json");
        urlConnection.setRequestMethod("POST");
        urlConnection.setInstanceFollowRedirects(false);


        OutputStream out = urlConnection.getOutputStream();
        //Thread.sleep(5000);
        writeStream(out);
        out.flush();

        InputStream in = urlConnection.getInputStream();
        readStream(in);
    } finally {
        urlConnection.disconnect();
    }

}

private static void writeStream(OutputStream out) {
    // TODO Auto-generated method stub
    try {
        JSONObject grp = new JSONObject();
        JSONObject gp = new JSONObject();
        gp.put("id", "g3bj25");
        gp.put("from", "someone");

        out.write(gp.toString().getBytes());

        System.out.println(gp.toString());
    } catch (IOException | JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

Do I have to make any changes in server side so that it waits for content?

saikat
  • 145
  • 1
  • 14

1 Answers1

0

The problem is, that your URL is not complete, the name of the script is missing.

URL url = new URL("http://127.0.0.1:8000/message/");

supposes that you are calling http://127.0.0.1/message/index.php but here you're not allowed to let the index.php (or whatever) implicit.

The script gets called, but the POST data is not sent, or it is truncated by the Webserver when handling the request. I had the same problem and spent hours until I found the reason. Then I did not dig further to find out exactly where the POST data gets dropped.

nhaggen
  • 301
  • 2
  • 8