【发布时间】:2014-07-02 00:59:23
【问题描述】:
我正在使用 Google Protobuf 将序列化的类发送到 http 服务器。执行此操作的命令是:message.SerializeToString(&out); 请注意我们正在序列化为字符串。服务器将完全相同的对象返回给我。
所以,在我的连接中:didReceiveData 方法,我正在获取数据。
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
{
if (self.receivingData) {
[self.dataReceived appendData:data];
}
}
在我的 connectionDidFinishLoading 方法中,我认为我需要将 NSMutableData (self.dataReceived) 放入 NSString。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
self.receivingData = NO;
NSLog(@"%@", self.dataReceived);
NSString *data = [[NSString alloc] initWithData:self.dataReceived encoding:NSASCIIStringEncoding]; // Wrong encoding ????
NSMutableDictionary *processedData = [NSMutableDictionary dictionaryWithCapacity:1];
[processedData setObject:data forKey:@"ImageData"];
NSNotificationCenter *processedNote = [NSNotificationCenter defaultCenter];
[processedNote postNotificationName:@"DataReceived" object:nil userInfo:processedData];
}
但我不确定要使用什么编码。当我发送数据时,它看起来像这样:
"\b\x01\x12\x04Lucy\x1a\xd4\xdc;\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\...... (There's more)
当我收到数据时,它看起来像这样:
<08011204 4c756379 1ad4dc3b ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ..... (There's more)
当我用上面的数据(编码 NSASCIIStringEncoding)初始化 NSString 时,我得到了这个:
LucyÔÜ;ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ....... (There's more)
最终,我需要使用 Google Protobuf 方法从字符串解析数据:message.ParseFromString(data);
我如何知道要使用哪种编码?
【问题讨论】:
-
http 标头上可能有编码数据。你已经检查了吗?
-
实际上,您收到的数据似乎与您发送的数据相同。但我认为您不应该将数据转换为字符串。
-
@HotLicks - 是的,我们正在测试 protobuf。这里唯一应该发生的事情是我发送对象并且服务器将其发送回来。序列化出来的protobuf方法是SerializeToString(),从序列化对象中解析的方法是ParseFromString。
-
ParseFromString 中的“字符串”一词并不是指 UTF32 字符串,而是
char*。
标签: c++ objective-c http nsstring protocol-buffers