我得到以下代码的错误:
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"];另外,我使用的是synchronousRequest。在这里使用异步请求有什么好处?另外,更新代码很困难,所以我将使用异步请求?
发布于 2014-04-06 21:26:16
这段代码太糟糕了。
好吧,这是垃圾,因为如果您的响应中有任何Unicode字符,它就会失败。
编译器会对此抱怨吗?我敢打赌是这样的。你应该在这里传递一个编码。同样,如果您不使用Unicode编码,如果您有一个包含Unicode字符的字符串,这将无法创建任何数据。
整个双重转换都是无稽之谈,因为NSJSONSerialization需要NSData,而您最初的响应是NSData,所以您所要做的就是接受响应并按原样给它NSJSONSerialization,从而节省大量的内存,大量的CPU时间,并且它完全避免了您引入的双重bug。
发布于 2014-04-06 18:31:21
当你在主线程上运行时,异步请求是非常有用的,主线程是UI线程。同步请求可能会导致您的用户界面在请求处于“广播状态”时变得自由。
对于异步请求,您将异步接收数据。当接收到数据时,将调用(委托协议的)方法,并在那里处理接收到的数据。
https://stackoverflow.com/questions/22892751
复制相似问题