Here is my problem :
I'm sending base64 encoded data to my server from an iOS device. But sometimes, data seem to arrive divided in two requests.
On the device side I do :
NSString *base64Data = [self base64forData:myData];
NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:myRequestURL]; //like www.myaddress.com/myPHP.php
[myRequest setHTTPMethod:@"POST"];
[myRequest setHTTPBody:[[NSString stringWithFormat:@"mydata=%@&type=%d",base64Data] dataUsingEncoding:NSASCIIStringEncoding]];
NSError *error = nil;
NSURLResponse *response = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:myRequest returningResponse:&response error:&error];
Here is the encoding function :
- (NSString*)base64forData:(NSData*)theData {
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i,i2;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
for (i2=0; i2<3; i2++) {
value <<= 8;
if (i+i2 < length) {
value |= (0xFF & input[i+i2]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
On my server side, in myPHP.php, I use : $_REQUEST['mydata'];
, $_REQUEST['type'];
and file_get_contents('php://input');
to retrieve my data.
In case of problem, the first time, php get the first part of the HTTPBody. And then, it's call a second time with the end of the request. I can see that file_get_contents('php://input');
do not receive entirely my HTTPBody. For example I can receive a part of mydata
in a first call, and then the end of mydata
with type
.
If I send :
mydata=blablabla&type=totototo
I can received it divided in
mydata=blab
labla&type=tototo
Is the problem on the device side? problem with converting data in base64? setting the HTTPBody with NSASCIIStringEncoding ? special char corrupting the data retrieved by my server?
Any help is welcome.