NSMutableData to NSString -如何知道HTTP响应使用哪种编码

NSMutableData to NSString - how to know which encoding to use for HTTP response

本文关键字:编码 响应 HTTP NSString to 何知道 NSMutableData      更新时间:2023-10-16

我正在使用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有一个很酷的答案,它显示了编码类型。太棒了。