Domanda

I'm sending a base64 encoded image to a server as part of a post request using NSMutableURLRequest. What I log as the post body and what the server receives are not the same thing. The server seems to get a truncated version, as though the connection aborts midway. See the code below:

NSString *dataStr = [NSString stringWithFormat:@"request_data=%@",reqStr];
NSLog(@"datastr is %@",dataStr);
NSData *dataForUrl = [dataStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"nsdata length is: %i",[dataForUrl length]);
[urlRequest setHTTPBody:dataForUrl];
[urlRequest setValue:[NSString stringWithFormat:@"%d", [dataForUrl length]] forHTTPHeaderField:@"Content-Length"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *res, NSData *data, NSError *err) {
    // ... 
}

The first log statement shows the correct data. I even took the base64 part of the string to http://www.motobit.com/util/base64-decoder-encoder.asp, decoded it as a jpg, and it is the correct image. The second log statement shows that the length is the right size (422624 when the picture was 422480, for example).

I can't find anything wrong with the connection details or the data. The phone makes the connection, sends some data, then either the phone stops sending or the server stops receiving. What could cause that?

Edit: link to sample data http://pastebin.com/BS9HjKhg

Edit2: The server or iOS is converting the +'s from the image to spaces. I'll post an answer when I figure out the right way to send it.

È stato utile?

Soluzione

I was able to compare a full sample from the server vs what xcode logged, and found the + converted to [space]. Since that was the only character having a problem and url encoding is buggy in iOS, I just did

NSString *dataStr = [NSString stringWithFormat:@"request_data=%@",[reqStr stringByReplacingOccurrencesOfString:@"+" withString:@"%2B"]];

The server is accepting them again. I'm still not sure whether the server was the problem or it was iOS. The other OS's that connect use the same application/x-www-form-urlencoded as their content type with no problems.

Altri suggerimenti

I would suggest doing the conversion from Base64 string into NSData through Nick Lockwood's Base64 class.

That

NSData *dataForUrl = [dataStr dataUsingEncoding:NSUTF8StringEncoding];

worries me a bit (even more after looking at how Base64 is implements the conversion)...

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top