请教一下为什么我这样 POST 总是会返回 400?

2018-12-29 11:49:54 +08:00
 codechaser
	try{
            String host = 地址就不贴出来了;
            int port = 8080;
            int updateDelay = 1000;
            Socket s = new Socket(host,port);
            s.setSoTimeout(5000);

            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//            PrintWriter buffW = new PrintWriter(s.getOutputStream());
            BufferedWriter buffW = new BufferedWriter(new OutputStreamWriter(dos,StandardCharsets.UTF_8));

            String data = "{\"service\":2,\"Id\":\"0\"}";

      
            String postHeader =
                    "POST / HTTP/1.1\r\n" +
                            "Host:"+" 地址就不贴出来了\r\n" +
                            "Content-Type:application/json" +
                            "\r\n";

            System.out.println(postHeader);
            
            buffW.write(postHeader);
            buffW.write(data);
            buffW.write("\r\n");

            buffW.flush();

            s.shutdownOutput();

            Thread.sleep(updateDelay);

            DataInputStream dis = new DataInputStream(s.getInputStream());

            byte[] recvStr = new byte[4096];

            dis.read(recvStr);

            System.out.println(new String(recvStr,StandardCharsets.UTF_8));

            buffW.close();
            dos.close();
            //switch
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("请求错误!");
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

返回的结果一直是:

HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
Connection: close
3651 次点击
所在节点    Java
7 条回复
codechaser
2018-12-29 11:54:54 +08:00
我在 header 后面加了`\r\n`,可以拿到返回的 json 信息,但是还会跟着 400 Bad Request.......
codechaser
2018-12-29 13:46:28 +08:00
紧跟着的 400 bad request 在将`s.shutdownOutput()`后就会消失。
zjp
2018-12-29 14:04:48 +08:00
粗看是漏了个\r\n
也没说普通浏览器请求是什么情况,万一这个 url 就是返回 400 的呢……简单的 debug 方式是抓包,和 http 客户端的请求对比
suler
2018-12-29 14:16:21 +08:00
之前和别人调试接口,post 碰到过 400,是参数传错了。现在记不得他后端是用什么写的了,不过你可以看看是不是这个情况。
yzpure
2018-12-29 14:22:03 +08:00
header 和 data 之间少一个空行,把最后 buffW.write("\r\n")上移一行。另外 header 最好加上 Content-Length
codechaser
2018-12-29 15:22:10 +08:00
@yzpure 谢谢老哥,的确是缺了个换行和 content-length。这两个加上就没问题了
checkzhzzzzz
2018-12-29 20:18:00 +08:00
400 参数错误

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/522220

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX