首先,我知道该怎么做一个典型的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");
});
}