这是发出请求的 Google Apps 脚本:
UrlFetchApp.fetch('https://user:password@sitename.com/api', {
method: 'put',
headers: { 'Accept': '*/*' },
payload: 'foo=bar&baz=qux'
});
可以成功发布到http://requestb.in/ , 用于检查:
PUT /1bfk94g1 HTTP/1.1
User-Agent: Mozilla/5.0 (compatible; GoogleDocs; script; +http://docs.google.com)
Host: requestb.in
Content-Type: application/x-www-form-urlencoded
Content-Length: 43
Connection: keep-alive
Accept-Encoding: gzip
Accept: */*
foo=bar&baz=qux
但当请求 URL 为 https://user:password@sitename.com/api
时失败。显示的唯一错误信息是 Bad request: https://user:password@sitename.com/api
。
我构建了一个 curl
命令,它产生完全相同的 HTTP 请求:
curl -XPUT \
-H 'Accept-Encoding: gzip' \
--user-agent 'Mozilla/5.0 (compatible; GoogleDocs; script; +http://docs.google.com)' \
-d foo='bar' \
-d baz='qux'\
https://user:password@sitename.com/api
成功发布到 https://user:password@sitename.com/api
。两个相同的请求怎么会有不同的结果?关于我的 Google Apps 脚本,我是否遗漏了什么?我试过使用调试器,但没有用。
最佳答案
UrlFetchApp
似乎还不支持在 URL 中使用凭据的请求。 Authorization
HTTP header 需要手动构建。以下作品:
var response = UrlFetchApp.fetch('https://sitename.com/api', {
headers: {
'Authorization': 'Basic ' + Utilities.base64Encode(user + ':' + password)
}
});
关于http - 使用 `UrlFetchApp` 的 PUT 请求返回 'Bad Request' 但 Google Apps 脚本之外的相同请求有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13633549/