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

标签 java http post gwt

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

最佳答案

在实际写入流并关闭流(writer.write())之前,我尝试获取响应代码(connection.getResponseCode())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();
    }

关于java - 为什么 HTTP POST 返回代码 400(错误请求)? HTTP POST 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29262364/

相关文章:

php - Curl 和 PHP - 如何通过 curl 通过 PUT、POST、GET 传递 json

PHP $_POST 数组为空,但是 $_GET 完好无损

php - 修改代码以获取旧帖子上方最近评论的帖子

java - 创建带有填充变量且没有任何 setter 或构造函数的对象

java - JSF - 如何在 <h :messages> in a visually appealing way? 中格式化我的全局消息

c# - HttpWebRequest 在代码中抛出异常但在浏览器中不抛出异常

Node.JS:处理后数据读取错误的正确方法是什么?

java - Apache无法加载weblogic模块

java - 如何在没有eclipse的服务器上在eclipse之外运行java程序

http - Node.js 套接字如何链接到页面,以便连接到套接字端口时输入的文本显示在页面上?