- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在使用这段代码时遇到了这个错误:
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。在这里使用异步请求有什么好处?此外,很难更新代码所以我将使用异步请求?
最佳答案
这段代码很糟糕。
您正在获取响应数据并使用 ASCII 编码将其转换为字符串。好吧,那是垃圾,因为如果您的响应中有任何 Unicode 字符,它将失败。
然后将字符串转换为 NSData 对象并传递 nil 字符串编码。编译器会提示吗?我敢打赌。你应该在这里传递一个编码。同样,如果您不使用 Unicode 编码,如果您有一个包含 Unicode 字符的字符串,这将无法创建任何数据。
整个双重转换是无稽之谈,因为 NSJSONSerialization 想要 NSData,而你的原始响应是 NSData,所以你所做的就是接受响应并按原样给它 NSJSONSerialization,节省大量内存,大量 CPU 时间,并且它完全避免了您引入的双重错误。
关于ios - 检测到不正确的 NSStringEncoding 值 0x0000。假设 NSASCIIStringEncoding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22892751/
我有一个 url,我要从中请求数据。这是代码。 urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSASCIIStringE
我的 cocoa GUI 中有一个字符串需要特殊的格式(字体、颜色等)。当然,我使用的是属性字符串。为了方便起见,我将字符串初始化为 RTF: NSString *inputString = @"Th
我有这个: 我用它来转换为 NSString: NSString *info = [[NSString alloc] initWithData:data encoding:NSASCIIString
我在使用这段代码时遇到了这个错误: NSMutableURLRequest *request = [ [[NSMutableURLRequest alloc] initWithURL:[NSU
我是一名优秀的程序员,十分优秀!