我有个问题。我需要将 base64 字符串转换为 JSON 字符串并将其传递给服务器。例如我有一个 base64 字符串/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/Z
我需要将其转换为 JSON 格式。我执行以下操作:
+(NSData *)prepareForUploading:(NSString *)base64Str
{
NSDictionary *dict=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:base64str, nil] forKeys:[NSArray arrayWithObjects:@"picture", nil]];
NSData *preparedData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
return preparedData;
};
这里我是怎么做的NSURLRequest
-(NSString *)uploadPict:(NSString *)pict
{
NSLog(@"Server: upload: called");
NSData *prepPictData=[[self class] prepareForUploading:pict];
NSString *preparedBase64StrInJSON=[[NSString alloc] initWithData:prepPictData encoding:NSUTF8StringEncoding];
//here I'm adding access token to request
NSString *post = [NSString stringWithFormat:@"accessToken=%@&object=%@", self.key, preparedBase64StrInJSON];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@upload.aspx", serverAPIPath]]];
[request setHTTPMethod:@"POST"];
[request setValue:@"postLength" forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//....
}
但是我从服务器收到“Base-64 字符数组的长度无效”。怎么了?如果我将令牌和 JSON 粘贴到http://hurl.it/并使用它发出请求 - 一切正常。
我认为问题在于/
base64 字符串中的符号以及 JSON 中的 / 符号。也许是这样的[postData length]
:如果我从 JSON 字符串中删除\/
字符:
9j4AAQSkZJRgABAQAAAQABAAD4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQHZ
请求将正常执行,但这个 base64 编码的字符串不一样。
请帮我解决这个问题