Reputation: 73
This is my code which uses POST request to retrieve data but i am not able to get the desired results. There is no problem in url because it is showing JSON output on browser.
NSString *urlString = @"my url string";
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"email_string\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n",allIOSContactsEmailAddresses] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:body];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (data!=nil)
{
NSArray* array=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(@"array=%@",array);
}
}];
it is showing array=(null) in console..
Upvotes: 0
Views: 509
Reputation: 19098
Your multipart message body is not properly setup.
After the last part (you have only one) there needs to be a "close-boundary-delimiter". So, before you set the body for the request, you need to append the delimiter:
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
Strictly, there's no need to close the "close-boundary-delimiter" with a CRLF ("\r\n").
There is no need to prepend the actual body value (allIOSContactsEmailAddresses) with a CRLF (you did not). This CRLF would count as body content. Actually, this can confuse the consumer.
Contrary, for text bodies, a closing CRLF may sometimes needed (depends on the server).
Note when adding a header, it must be closed with a CRLF (as you did). In order to close the header area a closing CRLF is required. Regarding this, your message is correct.
Upvotes: 1
Reputation: 708
I just tried to use your code, and it succeeded without any problem.
Therefore your problem is in the server you send the request to, or in your NSURLConnection delegate methods which are not implemented properly.
You should also post the sending code (NSURLConnection usage).
Upvotes: 1