首先,我知道該怎麼做一個典型的POST到谷歌與訪問令牌,如如何執行POST XML
$.post('https://accounts.google.com/o/oauth2/token', {
refresh_token: localStorage.refresh_token,
client_id: my_client_id,
grant_type: 'refresh_token'
}).done(...}).fail(...});
不過,現在我想插入一行到Google電子表格。這裏有兩種情況。
- 用戶點擊'使用Google登錄'並使用Google憑據進行身份驗證。然後,我的應用發送POST請求,將行插入Google雲端硬盤上的電子表格中。這當前沒有問題(即行被插入到電子表格中)。
- 我不使用戶進行身份驗證,而是使用存儲在服務器上的刷新令牌爲其帳戶獲取訪問令牌。然後我執行與(1)中完全相同的POST請求,但是它無提示失敗。
因此,看起來好像第一個場景是在我不在(2)中複製的幕後進行一些配置。 SpreadSheet API上的文檔說我需要設置授權標題才能將此行提交到電子表格。我不知道該怎麼做(我希望文檔給出了一個例子),但看起來我可以使用jQuery的ajax
方法中的beforeSend
設置手動設置標題。要提交到電子表格,請求的contentType
必須是application/atom+xml
,這意味着我需要使用$.ajax()
而不是更容易的$.post()
(我認爲)。
需要說明的是,當我通過官方登錄過程獲取訪問令牌(我目前不在請求中使用)時,一切正常。但它在第二種情況下不起作用。
我使用Postman跟蹤了一個類似的POST請求,並查看了標頭和cookie以查看是否有任何授權標頭,但我沒有看到它。我已經在一天內查看了很多信息,一直沒有弄清楚我需要做什麼。
該請求是由PhoneGap Android應用程序製作的,如果有問題的話。
如何將標題設置爲正確的憑據?
這裏是我的代碼:
function postRowFromDatabaseToGoogleSpreadsheet(row) {
var spreadsheetApiUrl = "https://spreadsheets.google.com/feeds/list/myspreadsheet-key/1/private/full";
var xml = "<entry xmlns='http://www.w3.org/2005/Atom' " +
"xmlns:gsx='http://schemas.google.com/spreadsheets/2006/extended'>" +
"<gsx:{0}>{1}</gsx:{0}>".format("id", row.id) +
"<gsx:{0}>{1}</gsx:{0}>".format("coverage", row.coverage) +
"<gsx:{0}>{1}</gsx:{0}>".format("date", row.date) +
"<gsx:{0}>{1}</gsx:{0}>".format("time", row.time) +
"<gsx:{0}>{1}</gsx:{0}>".format("comments", row.comments) +
"<gsx:{0}>{1}</gsx:{0}>".format("kwhr", row.kwhr) +
"<gsx:{0}>{1}</gsx:{0}>".format("mlwater", row.mlwater) +
"<gsx:{0}>{1}</gsx:{0}>".format("tabletid", row.tabletid) +
"</entry>";
console.log("Submitting to URI: " + spreadsheetApiUrl);
console.log("Xml to submit: \n" + xml);
$.ajax({
type: "POST",
//headers:
beforeSend: function(xhr) {
console.log("beforeSend");
console.log(xhr);
xhr.done(function() {
console.log(xhr.responseText);
console.log(xhr.getAllResponseHeaders());
}).fail(function() {
console.log("xhr failed...");
});
},
url: spreadsheetApiUrl,
data: xml,
contentType: "application/atom+xml",
crossDomain: true
}).done(function(response) {
console.log("post succeeded");
if (response == null) {
console.log("response was null");
} else {
console.log(response);
}
}).fail(function(error) {
console.log("post failed");
console.log(error);
}).always(function() {
console.log("post completed");
});
}