导航

Submitting HTTP Requests (iPhone)

Posted on 2010-12-08 15:11  山姆蜀黍  阅读(427)  评论(0编辑  收藏  举报

Jared Wiltshire  25th June 2010

IntroHTTP Request Icon

This article will explain how to send a HTTP request and get a HTTP response on iPhone using Objective C. This subject can often be over complicated so I feel it is important that I explain how to use HTTP requests in much simpler terms. 

I will explain what is required to send out a basic HTTP request and retrieve a response back from the server. 

Elements of a HTTP request

To construct our HTTP request we must first understand what essential elements are required. 

  • Content Type: the type of data you are sending, for example text/plain or image/jpeg
  • HTTP Method: either post or get depending on whether you are posting data to a form page or calling the HTTP simply for the purposes of retrieving a response from the server.
  • URL: the url you are sending the HTTP request to.
  • Content Length: the size in bytes of the HTTP body.
  • HTTP Body: if posting data to a page then this content is what the server will pick up.


Code Elements

The following are the classes that are required to piece together our HTTP request:
  • NSURL: Accepts a string of the URL
  • NSMutableURLRequest: Where the HTTP header fields (content type, content length, etc.) get set, along with the URL and the HTTP method.
  • NSMutableData: Used to store the HTTP body, an instantiation of this class allows for appending to, useful for an extra long HTTP body.


NSMutableURLRequest Diagram


You should be able to see from this diagram where all the HTTP elements are used by which classes. The elements around the outside are the descriptive names for the HTTP elements and show what classes they are stored in. 

Calling the HTTP request is done using the NSURLConnection class, allowing you to perform a synchronous request. Using this class allows you to specify the object that the response code string will be stored in and the object to store any error string returned by the HTTP request. 

The response needs to be stored in an instance of NSData ready for you to interpret, which you can then convert to a string and deal with the response. 

Let's look at some code that makes up a very basic HTTP request. First we will create our URL string, this should be the first thing you know anyway; 

       

        NSURL *oRequestUrl = [NSURL URLWithString:@"http://www.eigo.co.uk/Test-Submission.aspx"];

       



We need to add our HTTP headers but we have no request object. Create it by instantiating a new instance of the NSMutableURLRequest class; 

       

        NSMutableURLRequest *oRequest = [[[NSMutableURLRequest alloc] init] autorelease];

       


Now that we have the request object, lets add our HTTP headers and URL like so; 

       

        [oRequest setValue:@"text/plain" forHTTPHeaderField:@"Content-Type"];

        [oRequest setHTTPMethod:@"POST"];

        [oRequest setURL:oRequestUrl];

       


Note there are 3 different methods being used here – you need to specifiy the content-type using the forHTTPHeaderField but the HTTP method needs to be set specifically using the setHTTPMethod property. The URL needs to be set using the setURL method and accepts an instance of our NSURL object we created earlier. 

We need to create a HTTP Body, for our purposes let's enter a single line of text. Start by instantiating the NSMutable object and then append a single line of type NSString. 

       

        NSMutable oHttpBody = [NSMutableData data];

        [oHttpBody appendData:[@"This is Http Request body"             dataUsingEncoding:NSUTF8StringEncoding]];

       


I've leave it up to you what encoding you use, but for basic strings NSUTF8StringEncoding will suffice. 

Now that we have our HTTP Body; we can set the content length of the HTTP request as follows; 

       

        [oRequest setValue:[oHttpBody length] forHTTPHeaderField:@"Content-Length"];

       



Here we are accessing the NSMutable objects length property to obtain the size of the HTTP Body in bytes. Notice that we are using the same method that we did for the Content-Type to set the Content-Length. 

Finally we need to create a response object that will call the request and store a response code and response data (if any). This is done with the NSURLConnection object in conjunction with an NSDataobject. Make sure you first create an object to store the HTTP Response Code and HTTP Error (just incase one is returned). 

       

        NSError *oError = [[NSError alloc] init];

        NSHTTPURLResponse *oResponseCode = nil;

        NSData *oResponseData = [NSURLConnection sendSynchronousRequest:oRequest             returningResponse:oResponseCode error:oError];

       


Together the objects that are used to build up the response are: 

NSURLConnection Diagram


Once this NSURLConnection object is initialised with the above objects, the HTTP request begins. TheNSData object we created above will contain the response from the server (if any), but the response code is what we want which is contained in the NSHTTPURLResponse object. The NSURLConnection object will pass the HTTP status code into this object. 

We can check the status code by checking the status code value as follows; 

       

        If ([oResponseCode statusCode] >= 200)

        {

                NSLog(@"Status code is greater than 200");

        }

        


Any response data returned from the server will be contained in the NSData object that we created, we need to convert this NSData data type into a NSString data type. 

       

        NSString * strResult = [[NSString alloc] initWithData:oResponseData             encoding:NSUTF8StringEncoding];

       


That concludes what you need to get a HTTP Request out to a webpage or web service.