NSMutableData to NSString -如何知道HTTP响应使用哪种编码
NSMutableData to NSString - how to know which encoding to use for HTTP response
我正在使用Google Protobuf向http服务器发送序列化类。执行此操作的命令是:message.SerializeToString(&out);
注意,我们正在序列化成一个String对象。服务器将完全相同的对象返回给我。
因此,在我的connection: 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];
}
但我不确定使用什么编码。当我发送数据时,它看起来像这样:
"bx01x12x04Lucyx1axd4xdc;xffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxffxff...... (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)
当我用上面的数据初始化NSString(编码NSASCIIStringEncoding)时,我得到这个:
LucyÔÜ;ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ....... (There's more)
最后,我需要使用Google Protobuf方法从字符串解析数据: message.ParseFromString(data);
我如何知道使用哪种编码?
试试这个
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"%@", [response textEncodingName]);
}
我最终使用了以下代码:
const char *bytes = (const char *)[data bytes];
std::string byteString = std::string(bytes);
工作! !
但是@trick14有一个很酷的答案,它显示了编码类型。太棒了。
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 使用 MATLAB 编码器生成C++代码:编译错误"undefined reference to `rgb2gray_tbb_real64'"
- 在卡萨布兰卡形成编码参数的列表
- 使用C++进行游程编码
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 当服务中的事件被触发时,如何将响应从服务发送回客户端?
- 使用已使用 java 编码的 openssl 解码数据
- boost 是否有按特殊类型值编码状态"compact optional"?
- 如何在CPP的给定目录中列出UTF编码的文件名?
- 如何使用 C++将 ISO-2022-KR 编码转换为 UTF-8 编码?
- 绝对编码器十六进制输入
- 防止C++中的硬编码数字
- C++ 信号和插槽不工作:插槽不响应事件
- NodeJs 服务器充斥着 UDP 广播,不发送响应
- Qt中HTTP GET响应上的奇怪编码
- 用于计算来自不同实例的响应数的编码技术
- NSMutableData to NSString -如何知道HTTP响应使用哪种编码
- 无法以 latin1 编码样式生成响应 - 在 gsoap C++
- HTTP响应编码的包装器
- libcurl:检测块编码响应的块边界