NSURLConnection委托didReceiveData数据中的尾随字符

时间:2009-07-10 14:50:07

标签: iphone objective-c cocoa-touch

我真的很难弄清楚为什么我的网络服务调用充斥着垃圾数据。

我有一个UITableViewController,可以调用Web服务,也可以作为NSURLConnectionDelegate。

这是感兴趣的委托方法,请注意NSLog语句。

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"data %@", [[NSString alloc] initWithUTF8String: [data bytes]]);
    NSLog(@"before %@", [NSString stringWithUTF8String: self.rawData.bytes]);
    [self.rawData appendData:data];
    NSLog(@"after %@", [NSString stringWithUTF8String: self.rawData.bytes]);
}

以下是经过多次尝试后生成的日志:

2009-07-10 09:04:20.339 SundialInvoice[91493:20b] data {"items": [], "request": 

"/inventory/delivered.json"}
2009-07-10 09:04:20.339 SundialInvoice[91493:20b] before 
2009-07-10 09:04:20.340 SundialInvoice[91493:20b] after {"items": [], "request": "/inventory/delivered.json"} SundialInvoice] [PID 

2009-07-10 09:04:23.153 SundialInvoice[91493:20b] data {"items": [], "request": "/inventory/delivered.json"}l 4] [Mes
2009-07-10 09:04:23.154 SundialInvoice[91493:20b] before 
2009-07-10 09:04:23.154 SundialInvoice[91493:20b] after {"items": [], "request": "/inventory/delivered.json"} SundialInvoice] [PID 

2009-07-10 09:04:27.913 SundialInvoice[91493:20b] data (null)
2009-07-10 09:04:27.913 SundialInvoice[91493:20b] before 
2009-07-10 09:04:27.914 SundialInvoice[91493:20b] after {"items": [], "request": "/inventory/delivered.json"} SundialInvoice] [PID 

2009-07-10 09:04:30.486 SundialInvoice[91493:20b] data {"items": [], "request": "/inventory/delivered.json"}ice/1.0 CFN
2009-07-10 09:04:30.487 SundialInvoice[91493:20b] before 
2009-07-10 09:04:30.487 SundialInvoice[91493:20b] after {"items": [], "request": "/inventory/delivered.json"} SundialInvoice] [PID 

尾随垃圾数据来自何处?我已经多次使用curl运行web服务,垃圾不是来自它。

3 个答案:

答案 0 :(得分:11)

要从NSString创建NSData,您应该使用initWithData:encoding:,如下所示:

NSString *str = [[NSString alloc] initWithData:self.rawData
                                      encoding:NSUTF8StringEncoding];
NSLog(@"Before: %@", str);
[str release];

NSData字节视为C字符串可能会导致一些安全漏洞。

答案 1 :(得分:6)

我认为垃圾来自日志记录:

[NSString stringWithUTF8String:self.rawData.bytes]

这里你要说的是你想从这个C字符串中获得NSString(=以零结尾的字节数组)。问题是bytes NSData方法不会返回以零结尾的数据,因为它是普通数组,而不是C字符串。因此,NSString初始化程序甚至会在接收到的NSData结束后抓取字节,直到它达到先前存储在内存中的某个零字节。

答案 2 :(得分:1)

尝试以下方法:

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [rawData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%@",rawData);
}

还有什么声明rawData为???