Jacob Jacob - 1 month ago 16
HTTP Question

Why HTTP POST returns code 400 (bad request)? HTTP POST Method

Why server returns response code 400(bad request)?

URL serverAddress = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestMethod("POST");
int status = connection.getResponseCode(); // returns 400


For example this HTTP GET returns code 200:

/** Creating Connection **/
URL serverAddress = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestMethod("GET");
connection.setDoOutput(false);
int status = connection.getResponseCode(); // returns 200

Answer Source

I've tried to check response code before writing to OutputStream() thats why server returned Bad Request code(400). This is my code which works now:

            /** Creating Connection **/
            URL serverAddress = new URL(uri);
            HttpURLConnection connection = (HttpURLConnection) serverAddress.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", contentType);
            connection.setRequestMethod("POST");

            /** POSTing **/
            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery()); // should be fine if my getQuery is encoded right yes?
            writer.flush();
            writer.close();
            os.close();
            connection.connect();

            int status = connection.getResponseCode();
            PrinterClass.show(status);  //status
            if (status != 200)
                throw (new RESTfulWebServiceException("Invalid HTTP response status "
                    + "code " + status + " from web service server."));

private String getQuery() throws UnsupportedEncodingException
    {
        JSONObject jobj = new JSONObject();
        jobj.put("customerNumber", new JSONString("003"));
        jobj.put("mappingCode", new JSONString("jac_003"));
        jobj.put("name", new JSONString("johnny"));
        jobj.put("status", new JSONString("ACTIVE"));
        PrinterClass.show(jobj.toString());
        return jobj.toString();
    }