我已经用C#(Xamarin)编写了一个REST服务,该服务从API获得了令牌。我需要在Swift中使用相同的代码,我试图四处寻找,但找不到任何可靠的东西。看看下面的代码
public class RestService
{
HttpClient client;
public RestService()
{
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded "));
}
public async Task<Token> Login(User user)
{
string webUrl = Utility.AppConstant.ApiUrl + "/token";
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("grant_type", "password"));
postData.Add(new KeyValuePair<string, string>("username", user.Username));
postData.Add(new KeyValuePair<string, string>("password", user.Password));
var content = new FormUrlEncodedContent(postData);
var response = await PostResponseLogin<Token>(webUrl, content);
return response;
}
public async Task<T> PostResponseLogin<T>(string webUrl, FormUrlEncodedContent content) where T : class
{
try
{
var response = await client.PostAsync(webUrl, content);
var jsonResult = response.Content.ReadAsStringAsync().Result;
var responseObject = JsonConvert.DeserializeObject<T>(jsonResult);
return responseObject;
}
catch
{ return null; }
}
答案 0 :(得分:0)
Alamofire非常简单。
您的登录代码如下所示:
let parameters: Parameters = [
"grant_type":"password",
"username":user.Username,
"password":user.Password
]
Alamofire.request(AppConstant.ApiUrl + "/token", method: .post, parameters: parameters) response in {
// do something with the response
}
有几乎所有您需要的选项,包括反序列化。