objective-c - iOS/Objective C- 来自 NSMutableURLRequest 的空响应

标签 objective-c ios

这段代码:

NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnn.com"]];

[req setHTTPMethod:@"GET"];

NSURLResponse *res;
NSError *err;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&res error:&err];
NSString *html  = [NSString stringWithUTF8String:[data bytes]];

NSLog(@"email adress is %@ and password is %@, response is %@, length is %i", self.boxEmail.text, self.boxPassword.text, html, data.length);

对于 html 显示 null。出了什么问题?

NSLog'ing data.description 产生:

<3c21444f 43545950 45204854 4d4c3e0a 3c68746d 6c206c61 6e673d22 656e2d55 53223e0a 3c686561 643e0a3c

等等

最佳答案

您不能假定数据将以 NUL 终止,因此您不应调用 stringWithUTF8String。使用以下内容:

NSString *html  = [[NSString alloc] initWithData:data 
                                        encoding:NSUTF8StringEncoding];

如果您正在使用 ARC 或:

NSString *html  = [[[NSString alloc] initWithData:data 
                                         encoding:NSUTF8StringEncoding] autorelease]; 

否则。

关于objective-c - iOS/Objective C- 来自 NSMutableURLRequest 的空响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11856243/

相关文章:

ios - 地幔 iOS : How to create class model with variable key

ios - 设计一个可测试的 Objective-C 类

ios - 带有圆角图像的自定义 UIProgressView

ios - MKMapView 位置不会更新

ios - 无法从 init 系列中的方法中分配给自己?

c - 使用 c 以编程方式更改正在运行的外部进程的 uid 和 gid

iphone - MFMailComposeViewController 在 iOS5 中 dismissModalViewControllerAnimated 时崩溃

iphone - 从多个 UIButtons 调用一个选择器

ios - CMSampleBuffer 中的 UIImage 呈蓝色

ios - 格式字符串未使用数据参数?