浏览器给我http状态码200,而curl给我状态码301

时间:2019-05-01 20:09:30

标签: http curl

当我在网站上填写表格并使用Chrome Dev Tools对其进行检查时,会获得以下信息:

Response Headers:
HTTP/1.1 200 OK
Server: nginx
Content-Type: text/html;charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Status: 200 OK

Request Headers:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 53
Content-Type: application/x-www-form-urlencoded
DNT: 1
Host: www.32x8.com
Origin: http://www.32x8.com

Form Data:
in0: 0
calctype: pos
in1: 1
in2: 1
in3: 0
drawtype: htmlcss

这在浏览器中工作得很好,但是当我发出以下curl请求时:

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "in0=1&calctype=pos&in1=1&in2=1&in3=0&drawtype=htmlcss" -v http://www.32x8.com/circuits2

我得到以下输出:

...
* Connected to www.32x8.com (2605:de00:1:1:4a:3c:0:42) port 80 (#0)
> POST /circuits2 HTTP/1.1
> Host: www.32x8.com

< Server: nginx
< Status: 301 Moved Permanently
< Location: http://www.32x8.com/var2.html
...

我收到301响应。因此,我尝试在命令中添加-L标志以遵循所有重定向

curl -X POST -H "Content-Type: application/x-www-form-urlencoded" -d "in0=1&calctype=pos&in1=1&in2=1&in3=0&drawtype=htmlcss" -L -v http://www.32x8.com/circuits2

但是,这只是我的输出

...
> POST /circuits2 HTTP/1.1
> Host: www.32x8.com
> User-Agent: curl/7.52.1
> Accept: */*
> Content-Type: application/x-www-form-urlencoded
> Content-Length: 53
>
* upload completely sent off: 53 out of 53 bytes
< HTTP/1.1 301 Moved Permanently
< Server: nginx
< Date: Wed, 01 May 2019 19:54:49 GMT
< Content-Type: text/html;charset=utf-8
< Content-Length: 0
< Connection: keep-alive
< Status: 301 Moved Permanently
...
* Switch from POST to GET
...
> POST /var2.html HTTP/1.1
> Host: www.32x8.com
> User-Agent: curl/7.52.1
> Accept: */*
> Content-Type: application/x-www-form-urlencoded
>
< HTTP/1.1 405 Not Allowed
< Server: nginx
< Date: Wed, 01 May 2019 19:54:49 GMT
< Content-Type: text/html
< Content-Length: 173
< Connection: keep-alive
...

我得到405。 我在做什么错了?

1 个答案:

答案 0 :(得分:1)

这样,您实际上并没有做错任何事情,但是您正在经历HTTP的怪癖,该怪癖始于多年前,并且出于兼容性原因由cURL进行维护。

您正在向服务器发出POST请求,服务器正在响应301重定向消息。当您要求cURL遵循重定向时,它会这样做,但是会将POST更改为GET。这是过去几代浏览器继承的行为(我不理解这里的逻辑)。然后,您的服务器将GET请求拒绝为“不允许”。

您有两种可能的解决方法:301消息指示永久重定向,因此只需使用新地址(无论如何您都应该这样做)

或者,在您自己的代码中检测到301消息并亲自进行重定向,以便您可以发出正确的POST命令。这可能意味着您需要一个shell脚本,而不仅仅是cURL。