Objective C - POST data using NSURLConnection

16,243

Solution 1

This is a pretty simple HTTP request setup; if you have more specific questions you might do better asking those.

NSString *myParameters = @"paramOne=valueOne&paramTwo=valueTwo";

This sets up a string containing the POST parameters.

[myRequest setHTTPMethod:@"POST"];

The request needs to be a POST request.

[myRequest setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];

This puts the parameters into the post body (they need to be raw data, so we first encode them as UTF-8).

Solution 2

Step 1 : set URL definitions:

// Create the request

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.0.232:8080/xxxx/api/Login"]];

    // Specify that it will be a POST request
    request.HTTPMethod = @"POST";

    // This is how we set header fields
    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];

    [postDict setValue:@"Login" forKey:@"methodName"];
    [postDict setValue:@"admin" forKey:@"username"];
    [postDict setValue:@"123456" forKey:@"password"];
    [postDict setValue:@"mobile" forKey:@"clientType"];


    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];

    // Checking the format
    NSString *urlString =  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


    // Convert your data and set your request's HTTPBody property
    NSString *stringData = [[NSString alloc] initWithFormat:@"jsonRequest=%@", urlString];

    //@"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345678n\",\"clientType\":\"web\"}";

    NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];

    request.HTTPBody = requestBodyData;

    // Create url connection and fire request
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (!theConnection) {

        // Release the receivedData object.
        NSMutableData *responseData = nil;

        // Inform the user that the connection failed.
    }

Step 2: 

// Declare the value for NSURLResponse URL

//pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];

    NSError *error=nil;

    // Convert JSON Object into Dictionary
    NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:_responseData options:
                          NSJSONReadingMutableContainers error:&error];



    NSLog(@"Response %@",JSON);
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now

}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
}

Solution 3

The first line created an string, it can be replaced with:

NSString *myParameters = @"one=two&three=four";

It's written in initWithFormat so you can extend it to assign parameter value.

Second line indicate this is HTTP post request.

The third line, setHTTPBody method take NSData type, so you need to convert string type to NSData using dataUsingEncoding method.

Share:
16,243
achiral
Author by

achiral

Updated on June 14, 2022

Comments

  • achiral
    achiral almost 2 years

    I'm very slowly working my way through learning the URL loading system for iOS development, and I am hoping someone could briefly explain the following piece of code:

    NSString *myParameters = [[NSString alloc] initWithFormat:@"one=two&three=four"];
    [myRequest setHTTPMethod:@"POST"];
    [myRequest setHTTPBody:[myParameters dataUsingEncoding:NSUTF8StringEncoding]];
    

    Eventually I would like to be able to create an application that logs into my ISP's website and retrieves how much data I have left for the rest of the month, and I feel as though I should get my head around setHTTPMethod/setHTTPBody first.

    Kind regards

  • achiral
    achiral over 12 years
    Thanks for your response. As a follow-up, if I write an application that logs in to a website using a user name and password, how would I access data from the page that would ordinarily show up as a result of entering that data (i.e. the main page, rather than the login page)? Is it as simple as using the NSURLRequest to establish an NSURLConnection and then downloading the data?
  • csiu
    csiu over 12 years
    There are a few ways. You can put the info in NSURLCredentialStorage, provide it as part of the URL, or use the NSURLConnection delegate method connection:didReceiveAuthenticationChallenge:. I highly encourage you to check out the URL Loading System Programming Guide.
  • helsont
    helsont over 8 years
    This is the answer that demonstrates how to use NSURLConnection most fully.
  • Mathieu VIALES
    Mathieu VIALES over 6 years
    The "please try below code." sentence should not be within the code block. Also, please, explain what you're doing in the code so people that are new to the language have a chance to understand and use your code.