【发布时间】:2013-11-19 19:43:26
【问题描述】:
伙计们,
在 iOS 中,我想在身份验证后发送 API 链接的身份验证我想使用 Accept: application/json 处理另一个 JSON 请求 API
我该怎么做?
我尝试了这种方法,但它不起作用:
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL for authentication"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:120.0];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPMethod:@"POST"];
//[request setHTTPBody:data];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSLog(@"received authentication challenge");
NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"username"
password:@"pass"
persistence:NSURLCredentialPersistenceForSession];
NSLog(@"credential created");
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
NSLog(@"responded to authentication challenge");
// Second JSON Request API here
}
else {
NSLog(@"previous authentication failure");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"%@",response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
查看此链接
这是表演
{ “错误”: { "message": "Accept header 无效。需要通过 HTTP Header Accept: application/json", “类型”:“bad_request” } }
【问题讨论】:
标签: ios objective-c json authentication