Http Post请求被强制转换为Http Get请求

今天在开发一个服务的时候,发现用postman造的post请求,到了服务端变成了get请求。觉得很奇怪。于是打开wireshark抓包。

发现通信流程如下

1、post请求发起之后,服务端返回了302
在这里插入图片描述

2、客户端收到302之后,通过https向服务端发起了新的请求。 (wireshark抓包filter配置为:port 443 and host yourhost.com)
在这里插入图片描述

于是怀疑是客户端在处理302时,自动重新发起了get请求。

找了一下果然如此。

https://stackoverflow.com/questions/17605915/what-is-the-correct-behavior-expected-of-an-http-post-302-redirect-to-get

Note: RFC 1945 and RFC 2068 specify that the client is not allowed to change the method on the redirected request. However, most existing user agent implementations treat 302 as if it were a 303 response, performing a GET on the Location field-value regardless of the original request method. The status codes 303 and 307 have been added for servers that wish to make unambiguously clear which kind of reaction is expected of the client.

大多数http客户端(包括浏览器)会将引起302的原有的post请求转化为get请求发出去(其实这是将302当做303来处理)。

于是,将http换成https,问题解决。

至于为啥会将302当做303来处理,据说这是很多老服务器的期望行为。所以一切都是为了兼容。
————————————————
版权声明:本文为CSDN博主「tong_master」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tongtest/article/details/103517257

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java可以使用HttpURLConnection类来发送POST请求,具体步骤如下: 1. 创建URL对象,指定要访问的URL地址。 2. 调用URL对象的openConnection()方法,返回一个URLConnection对象。 3. 将URLConnection对象强制转换HttpURLConnection对象。 4. 设置请求方法为POST,调用setRequestMethod()方法。 5. 设置请求头信息,调用setRequestProperty()方法。 6. 设置请求体信息,调用getOutputStream()方法获取输出流,将请求参数写入输出流。 7. 发送请求,调用getInputStream()方法获取输入流,读取服务器返回的数据。 8. 关闭输入流和输出流,断开连接。 示例代码如下: ``` import java.io.*; import java.net.*; public class HttpPost { public static void main(String[] args) { try { // 创建URL对象 URL url = new URL("http://www.example.com"); // 打开连接 URLConnection connection = url.openConnection(); // 强制转换HttpURLConnection对象 HttpURLConnection httpURLConnection = (HttpURLConnection) connection; // 设置请求方法为POST httpURLConnection.setRequestMethod("POST"); // 设置请求头信息 httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length())); // 设置请求体信息 OutputStream outputStream = httpURLConnection.getOutputStream(); outputStream.write(data.getBytes()); outputStream.flush(); outputStream.close(); // 发送请求 InputStream inputStream = httpURLConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } bufferedReader.close(); inputStream.close(); // 断开连接 httpURLConnection.disconnect(); } catch (Exception e) { e.printStackTrace(); } } } ``` 其中,data为请求参数,可以根据实际情况进行修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值