AFNetworking base64参数,由NSJSONSerialization转义的字符

时间:2013-02-06 08:46:45

标签: ios json base64 afnetworking nsjsonserialization

我正在尝试使用AFNetworking将图像提交到CardShark's API

NSData *imageData = UIImageJPEGRepresentation(cardImage, 1.0);
NSDictionary *parameters = @{@"front" : [imageData base64EncodedStringWithSeparateLines:NO]};

NSString *path = [NSString stringWithFormat:@"cardShark?webhookUrl=%@&apiKey=%@", kCardSharkWebHookURLEncodedString, kCardSharkAPIKey];

[self postPath:path parameters:parameters
       success:^(AFHTTPRequestOperation *operation, id responseObject)
{
    completion(responseObject, nil);
}
       failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
    completion(nil, error);
}];

我已经尝试过base64字符串的所有组合。

base64EncodedStringWithSeparateLines:YES
base64EncodedStringWithSeparateLines:NO
base64EncodedString`

无效,在检查生成的请求上的HTTPBody后,我发现事情正在被转义。

原始base64以

开头

/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAAB AAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAEOKAD AAQAAAABAAACrAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB

但是一旦它通过AFNetworking并且可能是NSJSONSerialization,它就会被发布为

\/9j\/4AAQSkZJRgABAQAAAQABAAD\/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAEOKADAAQAAAABAAACrAAAAAD\/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH\/

正如您所见,/正在被转义。如何防止逃逸?通过另一个工具(la,curl)将确切的JSON主体传递给API会导致API产生错误。那么这里最好的方法是什么?

1 个答案:

答案 0 :(得分:0)

事实证明,这更多是API的错误。 AFNetworking具有以下代码,用于将Content-Type标头设置为charset=utf-8

case AFJSONParameterEncoding:;
                    [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
                    [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error]];
                    break;

出于任何我无法理解的原因,他们的API不支持标头上的charset属性。

话虽如此,他们很快就解决了这个问题,现在它正在修改上面显示的代码。