我在POSTMAN中尝试以下请求并通过Xcode
结果:从POSTMAN请求获取200响应,从Xcode获取1012
邮差:请求
请求类型:PUT
网址:https://www.somesite.com/v1/favorites
接头:
Content-Type:“application / json” 授权:AUTH_TOKEN
{
"requestParameters": {
"_id": 3598,
"favorites": [{
"_id": 1456,
"contactName": "aaa",
"contactUserName": "bbb"
}]
}
}
== Objective-C ==
NSURL* url = [NSURL URLWithString:URL_STRING];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"PUT"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
NSString *jsonPostBody = [NSString stringWithFormat:@"{\"requestParameters\":{\"_id\":%@,\"favorites\": [{\"_id\": %@,\"contactName\": \"%@\",\"contactUserName\":\"%@\"}]}}",USERID_STRING,CONTACT_ID_STRING,CONTACT_NAME_STRING,CONTACT_USERNAME_STRING];
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
[request setHTTPBody:postData];
[request setValue:AUTH_TOKEN forHTTPHeaderField:@"Authorization"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:handler];
我尝试打印jsonPostBody
字符串并验证它是有效的JSON
。任何人都可以通过指出是否有任何明显的我缺失的帮助来帮忙吗?
答案 0 :(得分:0)
-1012错误代码是NSURLErrorUserCancelledAuthentication。这听起来像是服务器请求的身份验证(通过401响应),但是您没有NSURLAonnection委托处理程序用于NSURLAuthenticationChallenge。也许auth标题不是很正确。
答案 1 :(得分:0)
自己找到答案。显然,Content-Type无效并取而代之 [请求setValue:@" application / json" forHTTPHeaderField:@"内容类型"];解决了这个问题。