为什么HTTP POST返回代码400(错误的请求)?HTTP POST方法

Jac*_*cob 0 java gwt post http

为什么服务器返回响应代码400(错误请求)?(不起作用)

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
Run Code Online (Sandbox Code Playgroud)

例如,此HTTP GET返回代码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
Run Code Online (Sandbox Code Playgroud)

Jac*_*cob 7

在我实际写入流并关闭流(writer.write()和os.close())之前,我试图获取响应代码(connection.getResponseCode()) 这就是为什么服务器返回错误请求代码(400) .这是我现在可以使用的代码:

            /** 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();
    }
Run Code Online (Sandbox Code Playgroud)