我使用的是 Mac 10.9.5 和 bash shell。我尝试通过 curl 提交请求,但尝试设置 content-type 标头时不断出现错误。下面我尝试
davea$ curl -v -o -H "Content-Type: application/json" -X POST -d '{"username”:”username”,”password”:”password”}’ http://localhost:8080/myproject/login
但 curl 返回“curl: (6) Couldn't resolve host 'Content-Type'”错误。以下是完整输出:
* getaddrinfo(3) failed for Content-Type:80
* Couldn't resolve host 'Content-Type'
* Closing connection 0
curl: (6) Couldn't resolve host 'Content-Type'
* Trying ::1...
* Connected to localhost (::1) port 8080 (#1)
> POST /myproject/login HTTP/1.1
> User-Agent: curl/7.40.0
> Host: localhost:8080
> Accept: */*
> Content-Length: 40
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 40 out of 40 bytes
< HTTP/1.1 302 Found
< Server: Apache-Coyote/1.1
< X-Content-Type-Options: nosniff
< X-XSS-Protection: 1; mode=block
< Cache-Control: no-cache, no-store, max-age=0, must-revalidate
< Pragma: no-cache
< Expires: 0
< X-Frame-Options: DENY
< Set-Cookie: JSESSIONID=B980765C84EA5759F743D1AAE8E189D0; Path=/myproject/; HttpOnly
< Location: http://localhost:8080/myproject/login?error
< Content-Length: 0
< Date: Mon, 06 Jul 2015 16:03:37 GMT
<
* Connection #1 to host localhost left intact
通过 curl 提交 content-type 标头的正确方法是什么?
答案1
通过 提交内容类型标头的正确方法是什么
curl
?
使用-H
您指定的参数:
-H "Content-Type: application/json"
另一方面,你有还指定了-o
(输出到文件)选项,但没有指定文件:
如果您想要 HTTP POST 或 PUT 请求的进度计,则需要使用 shell 重定向 (>)、-o [file] 或类似命令将响应输出重定向到文件。
(从man curl
)
因此命令变成:
$ curl -o output.txt -H "Content-Type: application/json" -X POST -d '{"username":"username","password":"password"}' http://localhost:8080/myproject/login
(注意:我还替换了上述命令中的智能引号,因为它们已经进入了你的问题)
应按您指定的方式提交标头和输出(至)。如果不需要,output.txt
您也可以省略该参数。虽然页面似乎没有指定它,但在测试中不能与混合。-o output.txt
man curl
-v
-o