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

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

为什么服务器 returns 响应代码 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

例如这个 HTTP GET returns 代码 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

错误 400 means Bad Request。您没有向我们展示您尝试请求的 URI,但是 URI 很可能只接受 GET 请求并且没有办法响应 POST 请求,因此它会抛出 400 错误.例如,使用 GET 请求显示照片列表的页面是有意义的,但是向所述页面发出 POST 请求根本没有意义。

另一种可能是您提供的内容类型不正确。通常,在发出 POST 请求时,您希望使用 application/x-www-form-urlencoded,这是您在 Internet 上提交任何网络表单时使用的内容类型。此外,您可能没有提供服务器需要的表单数据。想象这样一种情况,您尝试 post 在 Facebook 上发送一条消息,但您没有提供任何消息。服务器将正确地驳回您的空请求。

如果您向我们提供您正在使用的请求 URI 和内容类型,我们可以帮助您进一步调试。

查看合作伙伴通话的文档。 get操作显示所有伙伴,post操作需要设置一个body。你没有在你的代码中发送正文,因此你发送了一个错误的请求。

看这里: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

在我实际写入流并关闭流之前,我已经尝试获取响应代码 ( connection.getResponseCode() ) ( writer.write()os.close() ) 这就是服务器返回错误请求代码 (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();
    }

在我的例子中,我的 URL 字符串中有一个 space。我将其替换为 %20 并且有效。

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

对我来说,在我为 POST 请求设置 outputStream 值之前,它是从 inputStream 中读取的。我将 os.write()... 部分移至 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();
}