2

我正在尝试使用 AFNetworking 向CardShark 的 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\/

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

4

1 回答 1

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标题上的属性。

话虽如此,他们很快就解决了这个问题,现在它可以在没有修改上面显示的代码的情况下工作。

于 2013-02-06T22:22:41.503 回答