Search code examples
iphoneiosnsurlconnectionasihttprequestnsurlrequest

how to send post request with nsurlconnection


I have changed over to NSURLConnection and NSURLRequest delegates for my db connections etc. I was using the ASIHTTPRequest libraries to do all this stuff but finally decided to move on due to the lack of support for that 3rd party library.

what I am woundering is how do I send post requests to my db like you do with the ASIFormDataRequest as shown below

//This sets up all other request
        ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];

        [request setDelegate:self];
        [request setValidatesSecureCertificate:NO];
        [request setPostValue:@"ClientDataSet.xml" forKey:@"filename"];  
        [request startSynchronous];

i.e. how to do send the setPostValues with the NSURLRequest class? any help would be greatly appreciated


Solution

  • Using NSURLRequest is slightly more difficult than utilizing ASIHTTPRequest. You have to build your own post body.

    NSData *postBodyData = [NSData dataWithBytes: [postBodyString UTF8String] length:[postBodyString length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:yourURL]; 
    [request setHTTPMethod: @"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:postBodyData];