views:

1027

answers:

3

Can anyone paste some code on how to do an http post of a couple values?

+1  A: 

Second answer on a google search looks like what you probably need:

http://www.iphonedevforums.com/forum/sample-code/69-getting-content-url.html

Jason Coco
A: 

Here is some basic code that doest a POST call:

//url is the appropriate url for the http POST call
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
            [theRequest setHTTPMethod:@"POST"];

            NSURLConnection *theConnection = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
            if(theConnection)
            {
             webData = [[NSMutableData data]retain];
            }
            else
            {
             NSLog(@"theConnection is NULL");
            }

You need to implement the appropriate delegate methods of the NSURLConnection.

zPesk
A: 

// You can drive an NSURLConnection synchronously using sendSynchronousRequest:returningResponse:error: // but that will block the entire thread until the response is received

// thebodyData = payload sent to server (in the correct format) // theMimeType = mineType of the payload //url is the appropriate url for the http POST call

NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
        [theRequest setHTTPMethod:@"POST"];

        NSURLConnection *theConnection = [[NSURLConnection alloc]initWithRequest:theRequest delegate:self];
        if(theConnection)
        {
            webData = [[NSMutableData data]retain];
             // give the details of the payload -- mine time and body content.
            [theRequest setValue: theMimeType forHTTPHeaderField:@"Content-Type"];
            [theRequest setHTTPBody:theBodyData];

        }
        else
        {
            NSLog(@"theConnection is NULL");
        }

// the delegate methods templates...

 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [webData setLength:0];  // clear the data incase it was a redirect in between.
}

 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];  // collect the data from server as it comes in.
}

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    [[NSAlert alertWithError:error] runModal]; // report the error
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Once this method is invoked, "webData" contains the complete result
}
Mark Fleming