我希望在WP 7应用程序中实现一个ParseObject创建和获取。在WP8中我们有SDK,但是在WP7中,由于没有SDK,所以我们可以使用REST。得到是容易的,但在岗位上,我找不到锻炼。
curl命令是:
curl -X POST \
-H "X-Parse-Application-Id: xxxxxxxxxx" \
-H "X-Parse-REST-API-Key: xxxxxx" \
-H "Content-Type: application/json" \
-d '{"score":1337,"playerName":"Sean Plott","cheatMode":false}' \
https://api.parse.com/1/classes/GameScore如何将其转换为等效的WP7请求?
发布于 2014-07-07 17:06:17
让我们看一下创建用户的以下解析文档
curl -X POST \
-H "X-Parse-Application-Id: Your App ID" \
-H "X-Parse-REST-API-Key: Your REST API Key" \
-H "Content-Type: application/json" \
-d '{"username":"cooldude6","password":"p_n7!-e8","phone":"415-392-0202"}' \
https://api.parse.com/1/usersParse文档显示,您必须设置您的http请求标头(-H表示标头)来指定应用程序id和api键。还可以将内容类型作为application/json添加到标头中。
接下来,文档显示了包含用户名和密码的正文(这是-d所代表的内容)中的post内容。
因此,为了创建一个新用户,您必须正确地设置头和正文。您可以使用HttpWebRequest来处理这个问题。在下面的示例中,我们在Parse帐户上创建一个新用户。
创建新的用户帐户
public async Task<User> CreateUserAsync(User user)
{
// An anonymous Type that converts our properties to match the Parse API casing.
var anonymousUser = new
{
email = user.Email.ToLower(),
password = user.Password,
username = user.UserName.ToLower(),
userId = user.UserId,
};
// I use the Newtonsoft Json library to serialize the anonymous type to json
// which is what the server expects (due to ContentType=application/json).
string json = await JsonConvert.SerializeObjectAsync(anonymousUser);
// Next we set up our request URL, headers Content Type.
HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri("https://api.parse.com/1/users"));
request.Headers["X-Parse-Application-Id"] = "Your App ID";
request.Headers["X-Parse-REST-API-Key"] = "Your REST API Key";
request.ContentType = "application/json";
// Since we are sending information to the server, we have to set the Method to POST.
request.Method = "POST";
Open a stream writer using the response stream provided by our request.
using (var streamWriter = new StreamWriter(await request.GetRequestStreamAsync()))
{
// Write our Json to the server.
streamWriter.Write(json);
}
// Fetch a response from the server. This will give us back error codes or a successful code
var response = await request.GetResponseAsync();
string resultJson = string.Empty;
// Convert Read the Json response in to a string
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
resultJson = streamReader.ReadToEnd();
}
// Create an anonymous Type matching the response documented in the Parse API
var deserializedObject = new
{
createdAt = string.Empty,
objectId = string.Empty,
sessionToken = string.Empty,
};
// Deserialize in to our response object.
deserializedObject = JsonConvert.DeserializeAnonymousType(resultJson, deserializedObject);
// Save the session token provided so we can use it later.
// You will need to determine how you want to save this.
await SaveSessionTokenAsync(deserializedObject.sessionToken);
DateTime createdDate = DateTime.Now;
DateTime.TryParse(deserializedObject.createdAt, out createdDate);
user.CreatedDate = createdDate;
// Return the newly created user.
return user;
}用户模型
user模型非常简单。
public class User
{
public string Username {get; set;}
public string Password {get; set;}
public string Email {get; set;}
public Guid UserId {get; set;}
public DateTime CreatedDate {get; set;}
}Parse文档显示了您可以期望服务器作为响应返回的内容。
{
"createdAt": "2011-11-07T20:58:34.448Z",
"objectId": "g7y9tkhB7O",
"sessionToken": "pnktnjyb996sj4p156gjtp4im"
}我们使用上面的deserilizedObject匿名类型来模拟这个过程。这样我们就能捕捉到sessionToken。您可以获取该会话令牌并将其保存到本地磁盘。这样,每次用户重新打开应用程序时,您都可以将会话令牌传递给服务器,并让用户返回,而不必每次都让用户登录。
请注意,当前存储会话令牌有一个副作用,在生产过程中可能不会对任何人产生影响,但在开发过程中可能会有点烦人。如果创建新用户并保存会话令牌,然后从仪表板中删除用户,则会话令牌仍然有效,并返回缓存的用户。我报告说这是一个bug,Parse团队正在努力解决这个问题,但目前,从仪表板中删除一个用户并不会阻止保存的会话令牌继续工作。
恢复用户状态
Parse文档显示了得到一个用户的以下内容。
curl -X GET \
-H "X-Parse-Application-Id: Your App ID" \
-H "X-Parse-REST-API-Key: Your REST API Key" \
-H "X-Parse-Session-Token: pnktnjyb996sj4p156gjtp4im" \
https://api.parse.com/1/users/me这再次要求您设置一些标头,但不需要在正文中指定任何内容。通过将会话令牌按到url,您将获得一个用户(如果它存在)。然后,如果您保存了会话令牌,则可以使用以下方法来处理还原用户状态
public async Task<User> GetUserAsync()
{
// I will leave how you save/load the session to you.
string sessionToken = await LoadSessionTokenAsync();
HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri("https://api.parse.com/1/users"));
request.Headers["X-Parse-Application-Id"] = "Your app ID";
request.Headers["X-Parse-REST-API-Key"] = "Your REST API Key";
request.Headers["X-Parse-Session-Token"] = sessionToken;
request.Method = "GET";
var response = await request.GetResponseAsync();
string resultJson = string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
resultJson = streamReader.ReadToEnd();
}
var deserializedUser = new
{
username = string.Empty,
email = string.Empty,
userId = string.Empty,
createdAt = string.Empty,
};
deserializedUser = JsonConvert.DeserializeAnonymousType(resultJson, deserializedUser);
var user = new User
{
UserName = deserializedUser.username,
Email = deserializedUser.email,
};
// Handle data conversions
Guid guid = Guid.Empty;
DateTime createdDate = DateTime.Now;
Guid.TryParse(deserializedUser.userId, out guid);
DateTime.TryParse(deserializedUser.createdAt, out createdDate);
user.CreatedDate = createdDate;
user.UserId = guid;
return user;
}登录用户
最后,文档显示了用于服务的登录用户的以下内容。
curl -X GET \
-H "X-Parse-Application-Id: Your App ID" \
-H "X-Parse-REST-API-Key: Your REST API Key" \
-G \
--data-urlencode 'username=cooldude6' \
--data-urlencode 'password=p_n7!-e8' \
https://api.parse.com/1/login在此,我们不再提供任何机构。--数据-urlencode仅仅意味着您必须将此数据作为url的一部分传递。所以从本质上说,URL看起来像
https://api.parse.com/1/login/?username=cooldude6&password=p_n7!-e8为了演示这一点,我们再次启动了一个GET,但只是稍微调整了URL,以包含url编码的数据。
public async Task<User> LoginAsync(string username, string password)
{
string url = string.Format("https://api.parse.com/1/login?username={0}&password={1}", username, password);
HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri(url));
request.Headers["X-Parse-Application-Id"] = "Your App ID";
request.Headers["X-Parse-REST-API-Key"] = "Your REST API Key";
request.Method = "GET";
var response = await request.GetResponseAsync();
string resultJson = string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
resultJson = streamReader.ReadToEnd();
}
var deserializedUser = new
{
username = string.Empty,
email = string.Empty,
userId = string.Empty,
createdAt = string.Empty,
};
deserializedUser = JsonConvert.DeserializeAnonymousType(resultJson, deserializedUser);
var user = new User
{
UserName = deserializedUser.username,
Email = deserializedUser.email,
};
// Handle data conversions
Guid guid = Guid.Empty;
DateTime createdDate = DateTime.Now;
Guid.TryParse(deserializedUser.userId, out guid);
DateTime.TryParse(deserializedUser.createdAt, out createdDate);
user.CreatedDate = createdDate;
user.UserId = guid;
return user;
}查询
希望这能为您提供一个良好的基础,让您了解如何阅读他们的文档以及curl参数代表什么。根据我前面演示的内容,您应该能够在API中查询对象,而不会有太多问题。例如,文档显示了查询如下。
curl -X GET \
-H "X-Parse-Application-Id: Your App ID" \
-H "X-Parse-REST-API-Key: Your REST API Key" \
https://api.parse.com/1/classes/GameScore这不过是我们为用户所做的事情。在这种情况下,您不需要任何会话令牌。您只需使用上面的URL创建一个HttpWebRequest,设置头部并调用GetResponseAsync。
HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri("https://api.parse.com/1/classes/GameScore"));
request.Headers["X-Parse-Application-Id"] = "Your App ID";
request.Headers["X-Parse-REST-API-Key"] = "Your REST API Key";
request.Method = "GET";
var response = await request.GetResponseAsync();
string resultJson = string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
// Get the Json, now you can deserialize it in to what ever represents your object.
resultJson = streamReader.ReadToEnd();
}如果您想要执行条件查询,您只需使用一个编码的url,就像我们对用户名和密码所做的一样。
在本例中,我会将匿名类型序列化为Json并提供该类型。沿着这些路线的东西。
var query = new
{
playName = "Bob",
cheatMode = "false",
};
string json = JsonConvert.SerializeObject(query);
string url = string.Format("https://api.parse.com/1/classes/GameScore?where={0}", query);
HttpWebRequest request = HttpWebRequest.CreateHttp(new Uri(url));
request.Headers["X-Parse-Application-Id"] = "Your App ID";
request.Headers["X-Parse-REST-API-Key"] = "Your REST API Key";
request.Method = "GET";
var response = await request.GetResponseAsync();
string resultJson = string.Empty;
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
resultJson = streamReader.ReadToEnd();
}希望这有助于您开始使用API。有了这些示例,您应该能够使用每个Parse,而不会出现任何问题。
最后,下面的链接可以帮助您确定CURL选项代表什么。http://curl.haxx.se/docs/manpage.html
https://stackoverflow.com/questions/24408808
复制相似问题