这段代码:
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/