2012-11-29 165 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) 
    } 
});