【问题标题】:Java HttpServlet Body "HTTP/1.1 400 Bad Request" POSTJava HttpServlet 正文 \"HTTP/1.1 400 错误请求\" POST
【发布时间】:2022-11-25 10:20:21
【问题描述】:

问题:尝试复制我的时收到“Bad Request”在职的邮递员例子...

我有我的 Java HttpServlet 设置来发送 POST 请求。

我可以在邮差没问题:

...但在我的 Java 环境中,出现“Bad Request 400”错误 ->

//CONFIGURE CONNECTION
proxyConnection.setRequestMethod(method);
proxyConnection.setDoInput(true);
proxyConnection.setDoOutput(true);

        
JsonObject parent = new JsonObject();
parent.addProperty("client_id", "clientXXY");
parent.addProperty("client_secret", "jxx.2221122");
parent.addProperty("username", "API.PRODTEST");
parent.addProperty("password", "kkGGkkGGEEee1");
        
OutputStream os = proxyConnection.getOutputStream();
os.write(parent.toString().getBytes("UTF-8"));
os.close();

//ESTABLISH CONNECTION
proxyConnection.connect();

// ----> this throws "Bad Request"
System.out.println("ret mess " + proxyConnection.getResponseMessage() );

【问题讨论】:

  • 它们不一样,因此失败了。您正在从您的 java 部分发送来自邮递员和 json 的表单。这些是完全不同的事情,因此它失败了。
  • 感谢您的意见,并感谢任何类型的指向我的正确方向帮助/示例/链接或任何东西

标签: java servlets httprequest


【解决方案1】:

想为任何以错误方式做同样事情的人发布我的问题的答案。

是的,我需要将数据作为 String 参数发送,而不是 JSON,请参见以下代码 --->

(特别感谢M. Deinum指出来)

//CONFIGURE CONNECTION
proxyConnection.setRequestMethod(method);
proxyConnection.setDoInput(true);
proxyConnection.setDoOutput(true);

        
// JsonObject parent = new JsonObject();
// parent.addProperty("client_id", "clientXXY");
// parent.addProperty("client_secret", "jxx.2221122");
// parent.addProperty("username", "API.PRODTEST");
// parent.addProperty("password", "kkGGkkGGEEee1");
        
// OutputStream os = proxyConnection.getOutputStream();
// os.write(parent.toString().getBytes("UTF-8"));
// os.close();


        String proxyQuery = "client_id=x&client_secret=x&grant_type=password&username=API.x&password=x&acr_values=";

        byte[] postData = proxyQuery.getBytes( StandardCharsets.UTF_8 );
        int postDataLength = postData.length;
         
        proxyConnection.setRequestProperty("charset", "utf-8");
        proxyConnection.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
        proxyConnection.setUseCaches(false);
        try(DataOutputStream wr = new DataOutputStream(proxyConnection.getOutputStream())) {
           wr.write( postData );
        }


//ESTABLISH CONNECTION
proxyConnection.connect();

【讨论】:

    猜你喜欢
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 2015-04-10
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    相关资源
    最近更新 更多