Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 12th, 2012  |  syntax: None  |  size: 1.69 KB  |  hits: 8  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Issue posting data to web server with NSMutableURLRequest
  2. -(void)starting {
  3. NSURL *url = [NSURL
  4. URLWithString:@"http:myurl/myfile.txt"];
  5. NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
  6. urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; //Calling NSURLConnection delegate methods
  7. }
  8.        
  9. NSString *someString = @"Hello World";
  10. NSData* theData=[someString dataUsingEncoding:NSUTF8StringEncoding];
  11.  
  12. NSURL *someUrl = [NSURL URLWithString:@"http://myurl/myfile.txt"];
  13.        
  14. NSString *postLength = [NSString stringWithFormat:@"%d", [theData length]];
  15.  
  16. NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
  17. [request setURL:someUrl];
  18. [request setHTTPMethod:@"POST"];
  19. [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
  20. [request setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];    
  21. [request setHTTPBody:theData];
  22.        
  23. [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[someUrl host]];
  24.        
  25. NSError *error;
  26. NSURLResponse *response;
  27. NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  28. NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
  29.        
  30. if ([data length] == 0) {
  31.  
  32.     UIAlertView *dataLengthNoneAlert = [[UIAlertView alloc] initWithTitle:@"No data" message:@"There is no data on the server" delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil, nil];
  33.  
  34.     [dataLengthNoneAlert show];
  35.  
  36. }
  37.        
  38. else {
  39.  
  40.     NSLog(data);
  41.  
  42.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Retrieved data" message:data delegate:nil cancelButtonTitle:@"Dimiss" otherButtonTitles:nil, nil];
  43.  
  44.     [alert show];
  45.  
  46. }