简体   繁体   中英

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

Why server returns response code 400(bad request)? (doesn't work)

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: (works)

/** 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

I've tried to get response code ( connection.getResponseCode() ) before I did actually wrote to a stream and close the stream ( writer.write() and os.close() ) 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());
            writer.flush();
            writer.close();
            os.close();
            connection.connect();

            int status = connection.getResponseCode();//this cannot be invoked before data stream is ready when performing HTTP POST
            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();
    }

In my case, there was a space in my URL string. I replaced it with %20 and it worked.

    requestUrl = requestUrl.replace(" ", "%20");

Error 400 means Bad Request . You don't show us which URI you're trying to request, however it's quite possible that the URI accepts only GET requests and doesn't have a way to respond to a POST request, hence it throws a 400 error. For example, requesting a page that shows a listing of photos with GET makes sense, but making a POST request to said page makes no sense at all.

Another possibility is that you may be providing an incorrect content type. Usually, when making POST requests you want to use application/x-www-form-urlencoded , which is the content type that's used when you submit any web form on the internet. Furthermore, you may not be providing the form data that the server needs. Imagine a scenario where you try to post a message on Facebook but you've provided no message. The server will rightfully dismiss your empty request.

If you provide us with the request URI and content type you are using we can help you further in debugging this.

look into the documentation for the partner call. The get operation shows all partners, the post operation requires a body to be set. you dont send the body in your code, thus you send a bad request.

See here: http://nwb.sys.stage-cf-billing.swisslab.io/com.swisscom.nwb.cf.api/doc/swagger/index.html#!/Partner/GETPartner vs

http://nwb.sys.stage-cf-billing.swisslab.io/com.swisscom.nwb.cf.api/doc/swagger/index.html#!/Partner/POSTPartner

For me, it was reading from the inputStream before I set the outputStream values for POST request. I moved the os.write()... section just below the OutputSteam os = ...

String body = "\"key\": \"value\"";
StringBuilder stringBuilder = new StringBuilder();

OutputStream os = conn.getOutputStream();
try {
    byte[] input = body.getBytes("utf-8");
    os.write(input, 0, input.length);           
} catch(Exception ex) {
    ex.printStackTrace();
}

BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"))
try {
    String line = null;

    while ((line= br.readLine()) != null) {
        stringBuilder.append(line.trim());
    }
} catch(Exception ex) {
    ex.printStackTrace();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM