1

I have the following code, which should simply load a URL with post data, and then grab the HTML response from the server:

// Send log in request to server
NSString *post = [NSString stringWithFormat:@"username=%@&password=%@", text_field_menu_username.text, text_field_menu_password.text];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request;
[request setURL:[NSURL URLWithString:@"http://example.com/test.php"]]; // Example Only
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

[NSURLConnection sendAsynchronousRequest:request
                                   queue:[NSOperationQueue mainQueue]
                       completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
    // Handle response
    NSString *response_string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"Data 1: %@", response);
    NSLog(@"Data 2: %@", data);
    NSLog(@"Data 3: %@", error);
    NSLog(@"Data 4: %@", response_string);
}];

Here's the output from each of the NSLog's:

Data 1: (null)
Data 2: (null)
Data 3: (null)
Data 4: 

Any idea what I am doing wrong?

Peter Hosey
  • 95,783
  • 15
  • 211
  • 370
Wes Cossick
  • 2,923
  • 2
  • 20
  • 35

1 Answers1

2

You haven't initialized the request object before setting its parameters. It should be:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
omz
  • 53,243
  • 5
  • 129
  • 141
  • Perfect. And for anyone looking at this in the future, the `response_string` variable was the one that contained the correct response. – Wes Cossick Mar 08 '13 at 03:12