2012-11-29 164 views
1

这是谷歌Apps脚本发出请求:PUT请求工作

UrlFetchApp.fetch('https://user:[email protected]/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:[email protected]/api时失败。唯一显示的错误信息是Bad request: https://user:[email protected]/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:[email protected]/api 

成功地职位,以https://user:[email protected]/api。两个相同的请求怎么能有不同的结果?我错过了与Google Apps脚本有关的内容吗?我试过使用调试器,但它没有帮助。

回答

2

看起来UrlFetchApp还不支持URL中具有凭据的请求。 Authorization HTTP头需要手动建立。以下作品:

var response = UrlFetchApp.fetch('https://sitename.com/api', { 
    headers: { 
    'Authorization': 'Basic ' + Utilities.base64Encode(user + ':' + password) 
    } 
});