HTTP protocol (ii) HTTP request

Source: Internet
Author: User

I. Methods of HTTP Requests

In the http/1.1 protocol, 8 methods for sending HTTP requests are defined, with GET, POST, OPTION, HEAD, PUT, DELETE, TRACE, CONNECT, Pach. Depending on the interpretation of the HTTP protocol, different methods have different ways of manipulating resources:

1, PUT: Increase

2. Delete: Delete

3. POST: Change

4, GET: Check

One of the most commonly used when get and post. The main difference between get and post is in the delivery of data.

1. GET

After the URL in the form of a, to follow the parameters issued to the server, a number of parameters with & separated, such as:

http://localhost:8080/mjserver/login?username=name&pwd=123

Because the browser and server have a limit on the length of the URL, the parameters that are included with the URL are limited, usually no more than 1KB.

2. POST

Post-to-server parameters are placed in the request body, in theory there is no limit to the data size of post delivery.

3. How to Choose

If you want to pass large amounts of data, such as file uploads, you can only use post requests. Security, get is worse than post, if it contains some sensitive information recommended post, if only to obtain data from the server, such as query some information, we recommend the use of GET, if it is to add, modify and delete data, it is recommended to use post.

II. scenarios for sending HTTP requests in iOS

Apple's native solutions are:

1, Nsurlconnection--the use of a relatively simple direct approach.

2, Nsurlsession--ios 7 new technology, more powerful than the previous scheme

3, Cfnetwork--the solution of the bottom, pure C language

Third-party frameworks, more commonly used are:

1, ASIHTTPRequest: powerful, but has stopped updating

2, afnetworking: Simple and easy to use, provides a basic enough function.

In order to improve development efficiency, we recommend using a third-party framework.

1, Nsurlconnection

1. Common class:

Nsurl: Request Address

Nsurlrequest: Encapsulates a request to save all data sent to the server, including a Nsurl object, a request line, a request header, a request body, and so on.

Subclass of Nsmutableurlrequest:nsurlrequest

Nsurlconnection: Establish a connection between the client and the server, send the Nsurlrequest data to the server, and receive the response data from the server.

2, the use of nsurlconnection

Let's take a look at the code that gets the weather:

/** * Get weather information---asynchronous block*/- (void) GetWeatherInfo0 {//Show a Load boxMbprogresshud *hud =[Mbprogresshud showhudaddedto:[uiapplication sharedapplication].windows.lastobject Animated:YES]; Hud.labeltext=@"is loading"; Hud.dimbackground=YES; Hud.removefromsuperviewonhide=YES; //Send HTTP requestNSString *str =@"http://www.weather.com.cn/adat/sk/101010100.html"; Nsurl*url =[Nsurl Urlwithstring:str]; Nsurlrequest*request =[Nsurlrequest Requestwithurl:url]; [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] CompletionHandler:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {        //processing of the returned data, such as JSON parsingNsdictionary *dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil]; Nsdictionary*weatherinfodict = [Dict objectforkey:@"Weatherinfo"];                [Self weatherinfohandler:weatherinfodict];    [HUD Hide:yes];    }]; }/** * Processing obtained weather information * * @param weatherinfodict Weather Information*/- (void) Weatherinfohandler: (Nsdictionary *) weatherinfodict {//parse the retrieved content// CityNSString *city = [weatherinfodict objectforkey:@" City"]; UILabel*citylabel =[[UILabel alloc] init]; Citylabel.text= [NSString stringWithFormat:@"City:%@", City]; Citylabel.frame= CGRectMake ( the, -, -, -);    [Self.view Addsubview:citylabel]; //Release TimeNSString *time = [weatherinfodict objectforkey:@" Time"]; UILabel*timelabel =[[UILabel alloc] init]; Timelabel.text= [NSString stringWithFormat:@"release time:%@", TIME]; Timelabel.frame= CGRectMake ( the, -, the, -);    [Self.view Addsubview:timelabel]; //Wind DirectionNSString *WD = [weatherinfodict objectforkey:@"WD"]; UILabel*wdlabel =[[UILabel alloc] init]; Wdlabel.text= [NSString stringWithFormat:@"Wind:%@", WD]; Wdlabel.frame= CGRectMake ( the, Max, -, -);    [Self.view Addsubview:wdlabel]; //WindNSString *ws = [weatherinfodict objectforkey:@"WS"]; UILabel*wslabel =[[UILabel alloc] init]; Wslabel.text= [NSString stringWithFormat:@"Wind:%@", WS]; Wslabel.frame= CGRectMake ( the, the, -, -); [Self.view Addsubview:wslabel];}

First, you create a Nsurl object with an address that gets the weather, set the request path, and then use Nsurl to create a Nsurlrequest object, set the request header and the request body, and finally send nsurlrequest using Nsurlconnection.

The result is displayed:

There are several ways to send requests nsurlconnection:

1, asynchronous request, asynchronous request according to the way of data processing can be divided into 2 kinds:

A, block callback mode

+ (void) Sendasynchronousrequest: (nsurlrequest*) Request                          queue: (nsoperationqueue*) queue              Completionhandler: ( void (^) (nsurlresponse* response, nsdata* data, nserror* connectionerror)) Handler ns_available (10_7, 5_0);

Request is a constructed nsurlrequest, the queue is the thread behind the block processing, and the Completionhandler is the block where the retrieved data is processed.

B, Agent mode

/**/-(IDDelegate:(ID)delegate  startimmediately: ( BOOL) startimmediately ns_available (10_5, 2_0); -(IDDelegate:(ID)delegate; Delegate:(ID)delegate;

In this case, you need to call the Start method to start sending the request

-(void) Start ns_available (10_5, 2_0);

Become the agent of Nsurlconnection, according to the need to choose to comply with the appropriate agent

1 . Nsurlconnectiondelegate2. Nsurlconnectiondatadelegate3. Nsurlconnectiondownloaddelegate

The following is the code that sends the request using the agent processing method:

/** * Get weather Information---Asynchronous proxy method*/- (void) GetWeatherInfo1 {//Send HTTP requestNSString *str =@"http://www.weather.com.cn/adat/sk/101010100.html"; Nsurl*url =[Nsurl Urlwithstring:str]; Nsurlrequest*request =[Nsurlrequest Requestwithurl:url]; Nsurlconnection*connection = [[Nsurlconnection alloc] Initwithrequest:requestDelegate: Self startimmediately:no]; [Connection start];}#pragmaMark Proxy Callback-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) Data {nsdictionary*dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil]; if(dict) {nsdictionary*weatherinfodict = [Dict objectforkey:@"Weatherinfo"];    [Self weatherinfohandler:weatherinfodict]; }}
-(IDDelegate:(ID)delegate startimmediately: (BOOL) startimmediately Ns_ AVAILABLE (10_5, 2_0);

The startimmediately of this method, if yes, indicates that the download data is started immediately after the connection is established, and if no, the Start method is called to begin downloading the data.

2. Synchronous request

+ (NSData *) Sendsynchronousrequest: (nsurlrequest *) Request Returningresponse: (Nsurlresponse *) Response error: ( Nserror * *) error;

The response is the corresponding information, with the status line and the response first class response information. Here is the weather information obtained using a sync request:

/** * Get weather information---sync request*/- (void) GetWeatherInfo1 {//Send HTTP requestNSString *str =@"http://www.weather.com.cn/adat/sk/101010100.html"; Nsurl*url =[Nsurl Urlwithstring:str]; Nsurlrequest*request =[Nsurlrequest Requestwithurl:url]; Nsurlresponse*response =Nil; NSData*data = [Nsurlconnection sendsynchronousrequest:request returningresponse:&response Error:nil]; Nsdictionary*dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers Error:nil]; Nsdictionary*weatherinfodict = [Dict objectforkey:@"Weatherinfo"];        [Self weatherinfohandler:weatherinfodict]; //NSLog (@"Response%@", [response description]);}

The final log output is:

 -- -- Geneva  the: $:25.102httpdemo[1915:607] Response {url:http://www.weather.com.cn/adat/sk/101010100.html} {Status code:200, headers {    "accept-ranges"=bytes; Age=176; "Cc_cache"="Tcp_hit"; "Cache-control"="max-age=1800"; Connection="keep-alive"; "content-encoding"=gzip; "Content-length"=181; "Content-type"="text/html; Charset=utf-8"; Date="Thu, 07:54:29 GMT"; Expires="Thu, 08:25:49 GMT"; Server="apache/2.2.0"; "Set-cookie"="bigipserverwww_pool=1253639229.20480.0000; path=/";} }

Synchronous requests block the main thread, and typically the network requests common asynchronous requests. In addition, the request method of the HTTP request above is the default get method, if you want to change the request method and the request body can use Nsurlrequest subclass Nsmutableurlrequest, common settings are:

- (void) SetUrl: (Nsurl *) URL;//Set Request Address- (void) Setcachepolicy: (nsurlrequestcachepolicy) policy;//Set Cache policy- (void) Settimeoutinterval: (nstimeinterval) seconds;//setting the time-out period- (void) Sethttpmethod: (NSString *) method;//Set Request Method- (void) Setallhttpheaderfields: (Nsdictionary *) Headerfields;//set the request header field- (void) Sethttpbody: (NSData *) data;//set the request body


Finally attach the Demo:http agreement (ii) Demo

HTTP protocol (ii) HTTP request

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.