0

这段代码:

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。出了什么问题?

NSLog'ingdata.description产生:

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

等等

4

2 回答 2

5

您不能假设数据将被 NUL 终止,因此您不应该调用stringWithUTF8String. 使用以下内容:

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

如果您使用 ARC 或:

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

除此以外。

于 2012-08-08T01:19:03.843 回答
0

我通过复制和粘贴您的 html 代码得到以下信息:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
<title>CNN.com - Breaking News, U.S., World, Weather, Entertainment &amp; Video News</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8"/>
<meta http-equiv="last-modified" content="2012-08-08T00:48:58Z"/>
<meta http-equiv="refresh" content="1800;url=http://www.cnn.com/?refresh=1"/>
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8"/>
<meta name="robots" content="index,follow"/>
<meta name="googlebot" content="noarchive"/>
<meta name="description" content="CNN.com delivers the latest breaking news and information on the latest top stories, weather, business, entertainment, politics, and more. For in-depth coverage, CNN.com provides special reports, video, audio, photo galleries, and interactive guides."/>
<meta name="keywords" content="CNN,CNN news,CNN.com,CNN TV,news,news online,breaking news,U.S. news,world news,weather,business,CNN Money,sports,politics,law,technology,entertainment,education,travel,health,special reports,autos,developing story,news video,CNN Intl"/>
<meta name="application-name" content="CNN"/>
<meta name="msapplication-tooltip" content="Breaking News, U.S., World, Weather, Entertainment and Video News"/>
<meta name="msapplication-task" content="name=News Pulse;action-uri=http://newspulse.cnn.com/;icon-uri=http://www.cnn.com/favicon.ie9.ico"/>
<meta name="msapplication-task" content="name=iReport;action-uri=http://ireport.cnn.com;icon-uri=http://ireport.cnn.com/favicon.ico"/>
<meta name="viewport" content="width=1024"/>
<meta property="fb:app_id" content="80401312489"/>
<meta property="fb:page_id" content="129343697106537"/>
<link href="http://www.cnn.com/" rel="canonical"/>
<link href="http://www.cnn.com/favicon.ie9.ico" rel="Shortcut Icon" type="image/x-icon"/>
<link href="/tools/search/cnncom.xml" rel="search" title="CNN.com" 
.
.
.
于 2012-08-08T00:59:39.897 回答