【发布时间】:2014-04-06 21:51:14
【问题描述】:
我收到此代码的错误:
NSMutableURLRequest *request = [ [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:URL_LOGIN_API]] autorelease];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *responseData=[[NSString alloc] initWithData:urlData encoding:NSASCIIStringEncoding];
...
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:nil] options:NSJSONReadingMutableContainers error:&e];
用新代码编辑:
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSError *e = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:urlData options: NSJSONReadingMutableContainers error: &e];
NSString *response_code = [[dictionary objectForKey:@"data"] valueForKey:@"response"];
我也在使用同步请求。在这里使用异步请求有什么好处? 另外,更新代码很困难,所以我将使用异步请求?
【问题讨论】:
-
您检查 urlData 是否为空?或者 NSURLConnection 是否有任何错误?
-
是的。但它现在可以工作了,我将 NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:nil] options:NSJSONReadingMutableContainers error:&e] 替换为 NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[responseData dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&e];需要添加默认编码
标签: ios objective-c nsurlconnection nsmutableurlrequest