Amit Zoaretzs
Amit Zoaretzs

Reputation: 1

Sending Post http request from nsstring

I have this json:

{"myFriends":{"userId":"the user id", "userName":"the user name", "friends":[{"u":"friend user id","n":"friend user name"},{"u":"friend user id","n":"friend user name"}]}}

and I want to send him in post request to the server, this is the current way I am trying to do this:

+(NSData *)postDataToUrl:(NSString*)urlString :(NSString*)jsonString
{
    NSData* responseData = nil;
    NSURL *url=[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    responseData = [NSMutableData data] ;
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    NSString *bodydata=[NSString stringWithFormat:@"%@",jsonString];

    [request setHTTPMethod:@"POST"];
    NSData *req=[NSData dataWithBytes:[bodydata UTF8String] length:[bodydata length]];
    [request setHTTPBody:req];
    NSURLResponse* response;
    NSError* error = nil;
    responseData = [NSURLConnection sendSynchronousRequest:request     returningResponse:&response error:&error];
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

    NSLog(@"the final output is:%@",responseString);

    return responseData;
}

The json string contains the json, but for some reason the server always get nil and return error. How to fix this?

Upvotes: 0

Views: 293

Answers (2)

Diego
Diego

Reputation: 587

This is my code for POST request with an NSData parameter:

- (void)uploadJSONData:(NSData*)jsonData toPath:(NSString*)urlString {

    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:kRequestTimeout];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBody: data];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[data length]] forHTTPHeaderField:@"Content-Length"];

    // Create url connection and fire request
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
    [connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [connection start];
}

This is for an asynchronous request, but it should work just fine for synchronous. The only thing I see you might be missing is the "Content-Length" parameter.

Upvotes: 0

Rudi Angela
Rudi Angela

Reputation: 1473

It would certainly help to tell your server about the content type:

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

Furthermore: in my own code I use:

[request setHTTPBody:[bodydata dataUsingEncoding:NSUTF8StringEncoding]]

Upvotes: 1

Related Questions