0
HTTP POST请求SWIFT我尝试做POST请求到后端服务器,并使用这个基地会议一类“ServiceUtils”里面在Objective - C制作与会话
(AFHTTPSessionManager *)baseSessionManager {
if (httpSessionManager) {
return httpSessionManager;
}
httpSessionManager = [AFHTTPSessionManager manager];
httpSessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
[httpSessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[httpSessionManager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
// User agent for iOS app.
NSString *userAgent = [NSString stringWithFormat:@"xxxxx Mobile iOS/%@ (%@ - %@ v%@)", [Utils appVersionWithBuild], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion]];
[httpSessionManager.requestSerializer setValue:userAgent forHTTPHeaderField:@"User-Agent"];
// Mobile auth
User *user = [User getUserWithContext:[NSManagedObjectContext MR_defaultContext]];
NSString *mobileAuth = [[NSString stringWithFormat:@"%@--givemymoneybackdude", user.token] sha1];
[httpSessionManager.requestSerializer setValue:mobileAuth forHTTPHeaderField:@"Mobile-Auth"];
// Authorization
NSString *authorization = [[NSString stringWithFormat:@"%@:X", user.token] stringBase64];
[httpSessionManager.requestSerializer setValue:[NSString stringWithFormat:@"Basic %@", authorization] forHTTPHeaderField:@"Authorization"];
// Locale
if (user.locale) {
[httpSessionManager.requestSerializer setValue:user.locale forHTTPHeaderField:@"Accept-Language"];
}
return httpSessionManager;
}
这里是我的代码,试图使在SWIFT 2.3
if let url = NSURL(string: "xxxxxxxx") {
let session = ServicesUtils.baseSessionManager()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let jsonObject = ["token" : "Token String", "refresh_token" : "refresh_token String","expires_in" : "expires_in String", "user_id" : "uber_uuid", "token_type" : "Bearer"]
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: [])
session.dataTaskWithRequest(request) { data, response, error in
guard
error == nil &&
(response as? NSHTTPURLResponse)?.statusCode == 200
else {
print((response as? NSHTTPURLResponse)?.statusCode ?? "no status code")
print(error?.localizedDescription ?? "no error description")
return
}
}.resume()
POST请求尝试在此之后我得到这个错误:
请求失败:未经授权(401)
我检查了标题并且没问题,但是发生了这个问题。有人能告诉我为什么会发生这种情况吗?我怎么能通过jsonObject一个名为“集成”字典中包含的值
为什么在JSON数据发送令牌?它应该作为标题值传递。这不是一个解决方案,而是一个建议。 –
@TusharSharma由于来自Uber的集成,集成完成后我拿起信息并将其发送到后端 – breadevelopment
因此,您还获得任何身份验证令牌或其他东西? –