Posted By

lifedim on 11/05/09


Tagged

iphone


Versions (?)

Who likes this?

16 people have marked this snippet as a favorite

umang_nine
swapnonil
tbass134
charter
mracoker
stationstops
avanadra
rvachere
dannolan
bobbym245
sam_symons
FumarMata
djbabylon
ljayz
zhendalf
Tintenklecks


iphone HTTP request


 / Published in: Objective C
 

  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
Posted By: DavidsCreek on November 29, 2010

How do you grab this post on you php page when it has no name?

Posted By: aleks512 on December 15, 2010

Great post david, works great here, I had a small problem though, with the postBody, in my case I had to replace with something like this:

NSString *formData = [[NSString alloc] initWithFormat:@"", txtUsername.text, txtPass.text];

NSData *postData = [[NSString stringWithFormat:formData] dataUsingEncoding:NSUTF8StringEncoding];

in this way works perfectly fine,

Thanks,

Alex

You need to login to post a comment.