【发布时间】:2015-02-22 00:22:00
【问题描述】:
正如标题所说,我正在尝试使用 REST API 从 javascript(特别是 Appcelerator Android 应用程序)在 parse.com 上运行作业。我正在使用 REST,因为这只是用于诊断,我不想尝试让 parse.com javascript API 在 Appcelerator 中工作。问题是我无法通过身份验证。如果我没有传入身份验证标头,我会收到相应的 401 身份验证错误,但如果我设置了它们,我会收到“错误请求”。我已经通过 cURL 让它工作了,所以 URL 是正确的,并且 parse 会按预期响应调用。这是我的代码:
var url = "https://api.parse.com/1/jobs/sendMail";
var client = Ti.Network.createHTTPClient({
// function called when the response data is available
onload : function(e) {
Ti.API.info("Received text: " + this.responseText);
alert("Received text: " + this.responseText);
},
// function called when an error occurs, including a timeout
onerror : function(e) {
Ti.API.debug(e.error);
alert(e.error);
},
timeout : 5000 // in milliseconds
});
var param = {"text":msg};
// Prepare the connection.
var auth = {"app":"sTnsthoeunotreallymyappIDbutabunchofcharactersESnecu","key":"8ll5thisisntreallymykeyeitherhMKqkYG"};
client.open("POST", url);
client.setRequestHeader("X-Parse-Application-Id",auth.app);
client.setRequestHeader("X-Parse-REST-API-Key",auth.key);
client.setRequestHeader("Content-Type","application/json");
// Send the request.
client.send(param);
这是请求和响应:
POST https://api.parse.com/1/jobs/sendMail HTTP/1.1
X-Parse-Application-Id: myappid
User-Agent:
X-Parse-REST-API-Key: myrestapikey
Content-Type: application/json
X-Requested-With: XMLHttpRequest
Content-Length: 0
Host: api.parse.com
Connection: Keep-Alive
HTTP/1.1 401 Unauthorized
Access-Control-Allow-Methods: *
Access-Control-Allow-Origin: *
Cache-Control: no-cache
Content-Type: application/json; charset=utf-8
Date: Sun, 22 Feb 2015 04:36:11 GMT
Server: nginx/1.6.0
Set-Cookie: _parse_session=BAh7BkkiD3Nlc3Npb25faWQGOgZFRiIlMTY4MzY0NTZlOWQ3ZGRjZDJkOWQwMjA4MWZjNWViMTY%3D--ffc760efbe32aa80a5e6d369606361413433fa72; domain=.parse.com; path=/; expires=Tue, 24-Mar-2015 04:36:11 GMT; secure; HttpOnly
Status: 401 Unauthorized
WWW-Authenticate: Basic realm="Parse"
X-Content-Type-Options: nosniff
X-Runtime: 0.018320
X-UA-Compatible: IE=Edge,chrome=1
Content-Length: 24
Connection: keep-alive
{"error":"unauthorized"}
【问题讨论】:
-
您可以尝试通过 Runscope 转发您的请求,然后对 cUrl 执行相同的操作,然后使用 Runscope 进行并排比较,以尝试找出它在您的 Android 应用中不起作用的原因。
-
客户端可以添加其他默认标题。您将需要打开日志记录(Wire & headers)或查看服务器日志以确切了解正在发送的内容。与 curl 相同的标头 n 线,您将获得相同的结果
-
我添加了对问题的请求和响应。我使用 Fiddler 来实现这一点 - 似乎比 Runscope 更简单。但是,当我使用 cURL(或 ping)时,Fiddler 没有显示任何内容,所以我不确定有什么区别。我已经在 Windows 7 上安装了 cURL 客户端——知道为什么 Fiddler 不会向我显示该流量吗?经过一番搜索,我没有找到任何答案,但我会继续寻找。
标签: android rest parse-platform appcelerator