
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= Connection: close 1 codechaser OP 我在 header 后面加了`\r\n`,可以拿到返回的 json 信息,但是还会跟着 400 Bad Request....... |
2 codechaser OP 紧跟着的 400 bad request 在将`s.shutdownOutput()`后就会消失。 |
3 zjp Dec 29, 2018 via Android 粗看是漏了个\r\n 也没说普通浏览器请求是什么情况,万一这个 url 就是返回 400 的呢……简单的 debug 方式是抓包,和 http 客户端的请求对比 |
4 suler Dec 29, 2018 之前和别人调试接口,post 碰到过 400,是参数传错了。现在记不得他后端是用什么写的了,不过你可以看看是不是这个情况。 |
5 yzpure Dec 29, 2018 header 和 data 之间少一个空行,把最后 buffW.write("\r\n")上移一行。另外 header 最好加上 Content-Length |
6 codechaser OP @yzpure 谢谢老哥,的确是缺了个换行和 content-length。这两个加上就没问题了 |
7 checkzhzzzzz Dec 29, 2018 400 参数错误 |