Teja Nandamuri
Teja Nandamuri

Reputation: 11201

NSData is returning 0 bytes

I am trying to do a simple POST request. However the results seem different in POSTMAN plugin in chrome and in iOS simulator.

Here is the snapshot from POSTMAN:

enter image description here

enter image description here

As you can see, I get the JSON data in retun.

Here is my code to do the POST request:

    NSError *error;
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    NSURL *url = [NSURL URLWithString:kPostURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                                                           cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                       timeoutInterval:60.0];

    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

    [request setHTTPMethod:@"POST"];


    NSString *params =[[NSString alloc] initWithFormat:@"fname=%@&lname=%@&email=%@&password=%@&switchid=%d&didflag=%@",fname,lname,email,pass,switchid,flag];

    [request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        NSLog(@"response is %@",response);
        NSLog(@"erros is %@",error);

        NSMutableDictionary * innerJson = [NSJSONSerialization
                                           JSONObjectWithData:data options:kNilOptions error:&error
                                           ];
        NSLog(@"JSON data is %@",innerJson);

    }];

    [postDataTask resume];

And when I try to print the values in debugger, I get

JSON as null and NSData as 0 bytes. But I get the status code as 200 which is a success.

HEre is the response I get:

      { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Length" = 0;
    "Content-Type" = "text/html";
    Date = "Thu, 25 Feb 2016 02:04:02 GMT";
    "Keep-Alive" = "timeout=5";
    Server = "Apache/2.4.12";
    "X-Powered-By" = "PHP/5.5.30";
} }

Why do I get NSData as 0 bytes ?

Upvotes: 1

Views: 731

Answers (1)

Casey
Casey

Reputation: 6701

in the request in chrome you have the parameters as URL params. in the ObjC version you are adding the params as part of the post.

instead of adding the the params as part of the body:

[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

add it as part of the query:

NSURL *url = [NSURL URLWithString:[kPostURL stringByAppendingFormat:@"?%@", params]];

Upvotes: 2

Related Questions