Get and post requests for iOS development practices

Source: Internet
Author: User

Get and post requests for iOS development practices

Get and post requests are the most common way of HTTP requests. Familiarize yourself with the HTTP communication process before you say the request method:

Request

1. Request line: Request method, request path, version of HTTP protocol

Get/mjserver/resources/images/1.jpg http/1.1

2. Request header: Some descriptive information of the client

Host: 192.168.1.111:8080//Client address of the server you want to access

user-agent: mozilla/5.0 (Macintosh; Intel Mac OS X 10.9) firefox/30.0//client-type, client-side software environment

Accept: text/html,//The type of data that the client can receive

accept-language: ZH-CN//Client language environment

accept-encoding: gzip//client-supported data compression format

3. Request Body: Post request only this thing

Request parameters, data sent to the server

Response

1. Status line (response line): Version of HTTP protocol, response status Code, response status description

Server: apache-coyote/1.1//Type of server

content-type: image/jpeg//type of return data

content-length: 56811//length of returned data

Date: Mon, June 12:54:52 GMT//Response time

2. Response header: Some descriptive information about the server

Content-type: The content type returned to the client by the server

Content-length: The length of the content returned to the client by the server (such as the size of the file)

3. Entity content (response body)

The server returns specific data to the client, such as file data

Nsmutableurlrequest (Note: Non-nsurlrequest because this object is immutable)

1. Set timeout time (default 60s)

Request.timeoutinterval = 15;

2. How to set the request

Request. HttpMethod = @ "POST";

3. Set the request body

Request. Httpbody = data;

4, set the request header for example, the following is the JSON data of the table header settings

[Request setvalue:@ "Application/json" forhttpheaderfield:@ "Content-type"];

Get and Post comparisons:

Get (the default is a GET request):

Features: The Get method submitted parameters are directly stitched into the URL request address, multiple parameters are separated by &. Example: http://localhost:8080/myService/login?username=123&pwd=123

Disadvantages:

1, all the request data is exposed in the URL, not too safe

2, because the browser and server on the length of the URL is limited, so the parameters attached after the URL is limited, usually not more than 1KB

-(ibaction) Login {nsstring *loginuser = Self.userName.text;    NSString *loginpwd = Self.pwd.text; if (loginuser.length==0) {[Mbprogresshud showerror:@] Please enter your username!        "];    Return } if (loginpwd.length==0) {[Mbprogresshud showerror:@] Please enter your password!        "];    Return           }//Add mask [Mbprogresshud showmessage:@ "is logged in ..."]; The default is Get mode request: Get way parameter stitching directly into URL nsstring *urlstr = [NSString stringwithformat:@ "Http://localhost:8080/myService/login        ? username=%@&pwd=%@ ", Loginuser,loginpwd];        Post method request, the parameter is placed in the request body//nsstring *urlstr = @ "Http://localhost:8080/myService/login"; URL transcoding urlstr = [Urlstr stringbyaddingpercentencodingwithallowedcharacters:[nscharacterset         Urlqueryallowedcharacterset]];        URLSTR = [Urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];        Nsurl *url = [Nsurl urlwithstring:urlstr];        Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url]; Set the time-out (default 60s) request.timeoutinterval = 15; Set the request method requests.        HttpMethod = @ "POST";    Set the request body nsstring *param = [NSString stringwithformat:@ "username=%@&pwd=%@", loginuser,loginpwd]; NSString--NSData request.         Httpbody = [param datausingencoding:nsutf8stringencoding];        Set the request header information [requesting setvalue:@ "iphone" forhttpheaderfield:@ "User-agent"]; [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse * _nullable response, NSData * _nullable data, Nserror * _nullable connectionerror) {//Hide mask [        Mbprogresshud Hidehud]; if (Connectionerror | | data==nil) {[Mbprogresshud showerror:@] Network busy! Try again later!            "];        return; }else{nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Err            Or:nil];            NSString *error = dict[@ "Error"]; if (error) {[Mbprogresshud showerror:eRror];                }else{nsstring *success = dict[@ "Success"];            [Mbprogresshud showsuccess:success];        }        }    }]; }

POST

Characteristics:

1. Place all request parameters in the request body (httpbody)

2, theoretically, the size of the data sent to the server is not limited

3, the request data is relatively safe (no absolute security)

 1.URL Nsurl *url = [Nsurl urlwithstring:@ "Http://localhost:8080/myService/order"];        Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];    Request.timeoutinterval = 15; Request.        HttpMethod = @ "POST"; Nsdictionary *orderinfo = @{@ "shop_id": @ "1111", @ "Shop_na    Me ": @" where ", @" user_id ": @" 8919 "};    NSData *json = [nsjsonserialization datawithjsonobject:orderinfo options:nsjsonwritingprettyprinted Error:nil]; Request.        Httpbody = JSON;        5. Set the request header: This time the data of the request body is no longer a normal parameter, but a JSON data [request setvalue:@ "Application/json" forhttpheaderfield:@ "Content-type"]; [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse * _nullable response, NSData * _nullable data, Nserror * _nullable connectionerror) {if (Connectioner Ror | | Data==nil) {[MB]Progresshud showerror:@ "The network is busy! Try again later!            "];        return; }else{nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves ER            Ror:nil];            NSString *error = dict[@ "Error"];            if (error) {[Mbprogresshud showerror:error];                }else{nsstring *success = dict[@ "Success"];            [Mbprogresshud showsuccess:success]; }        }    }];

URL transcoding problem (cannot include Chinese in URL)

1. This method is obsolete

NSString *urlstr = [NSString stringwithformat:@ "http://localhost/login?username= drink &pwd=123"];urlstr = [urlstr Stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

2, the official recommended use:

NSString *urlstr = [NSString stringwithformat:@ "http://localhost/login?username= drink &pwd=123"];    URLSTR = [Urlstr stringbyaddingpercentencodingwithallowedcharacters:[nscharacterset URLQueryAllowedCharacterSet]];

Get and post requests for iOS development practices

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.