【发布时间】:2017-08-10 08:29:56
【问题描述】:
我在调用我们的 RESTful API 时遇到问题。请求是从 API 中获取令牌;我需要该令牌才能使用它来进一步调用该 API。
问题是,每当我拨打电话时,我都会收到 HTTP 403 状态代码,但我不知道为什么。我正在从 Android 拨打相同的电话,但它们工作正常,没有任何问题。
实际上我完全没有使用 xCode 的经验;我只是在其他开发人员编写的现有代码中实现一些更改。我不知道是我做错了什么还是什么。
id keys[] = {@"grant_type", @"client_id", @"client_secret", @"username", @"password"};
id objects[] = {@"password", @"AppClientID", @"AppClientSecret", @"usernamehere", @"userpasswordhere"};
NSUInteger count = sizeof(objects) / sizeof(id);
NSDictionary *d = [NSDictionary dictionaryWithObjects:objects forKeys:keys count:count];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:NSJSONWritingPrettyPrinted error:nil];
NSURL *url = [NSURL URLWithString:@"https://oauth-test.websitename.com/token"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:60];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"Basic" forHTTPHeaderField:@"Authorization"];
[request setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError) {
if(data.length > 0 && connectionError == nil) {
NSLog(@"Response --> %@ ", response);
}
}
];
有人可以帮我弄清楚到底出了什么问题吗? 提前致谢。
【问题讨论】:
-
您应该使用 URLSession,因为 NSURLConnection 在 iOS 10 中已被弃用
-
它能解决我的问题吗?还是只是一个建议?
-
这是一个建议,你可以试试
-
你能显示日志的结果吗?
-
感谢富维!您建议的解决方案有效。