iphone HTTP request


/ Published in: Objective C
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //prepar request
  2. NSString *urlString = [NSString stringWithFormat:@"http://urlToSend.com"];
  3. NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
  4. [request setURL:[NSURL URLWithString:urlString]];
  5. [request setHTTPMethod:@"POST"];
  6.  
  7. //set headers
  8. NSString *contentType = [NSString stringWithFormat:@"text/xml"];
  9. [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
  10.  
  11. //create the body
  12. NSMutableData *postBody = [NSMutableData data];
  13. [postBody appendData:[[NSString stringWithFormat:@"<xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
  14. [postBody appendData:[[NSString stringWithFormat:@"<yourcode/>"] dataUsingEncoding:NSUTF8StringEncoding]];
  15. [postBody appendData:[[NSString stringWithFormat:@"</xml>"] dataUsingEncoding:NSUTF8StringEncoding]];
  16.  
  17. //post
  18. [request setHTTPBody:postBody];
  19.  
  20. //get response
  21. NSHTTPURLResponse* urlResponse = nil;
  22. NSError *error = [[NSError alloc] init];
  23. NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
  24. NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
  25. NSLog(@"Response Code: %d", [urlResponse statusCode]);
  26. if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) {
  27. NSLog(@"Response: %@", result);
  28.  
  29. //here you get the response
  30.  
  31. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.