【发布时间】:2017-04-10 11:31:31
【问题描述】:
我已经使用 POST 方法在我的应用程序中调用带有标头值和参数的 API。 但在我的后端无法让我的标头值进行身份验证。甚至我的回复也有无效用户。我附上了我的sn-p。你能帮我解决这个问题吗?
NSString *post = [NSString stringWithFormat:@"test=Message"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
[request setURL:[NSURL URLWithString:@"http://myURL.com/FakeURL"]];
[request setHTTPMethod:@"POST"];
NSString *authStr=[NSString stringWithFormat:@"userName:xxx"];
NSData *authData=[authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *headerValue=[NSString stringWithFormat:@"Basic %@",[authData base64EncodedStringWithOptions:0]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setValue:headerValue forHTTPHeaderField:@"Authorization"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(@"requestReply: %@", requestReply);
我的回复是:
2017-04-10 16:43:35.635 Testing[5155:172935] ST :200
2017-04-10 16:43:35.636 API_Testing_AeroVoyce[5155:172935] Error :(null)
2017-04-10 16:43:35.638 API_Testing_AeroVoyce[5155:172935] requestReply :invalid user
【问题讨论】:
-
你是如何传递 URL 的?
-
@AbilashBNair 抱歉,现在我更新了 URL myURL.com/FakeURL
-
它可以与 POSTMAN 一起使用吗?
-
看看如何在目标 C 中添加标头。我认为这是您在构建请求时遇到问题的地方。尝试断点以了解您发送的真实请求。 stackoverflow.com/a/5116201/6203030
-
headerValue是否与您在 POSTMAN 上的相同?既然你有application/x-www-form-urlencoded,你有没有添加那个标题?
标签: ios object authentication http-post nsurlsession