iOS Development-get requests, post requests, synchronous requests, and asynchronous requests

Source: Internet
Author: User

the Get and post in the header are two ways of requesting, synchronous and asynchronous are implementations, and get methods are synchronous and asynchronous, and there are two kinds of post. A little bit of web knowledge, to get and post should not be unfamiliar, often said request processing response, basically request is the two buddies, HTTP is the first definition of the server interaction with the way there are eight kinds, but with the evolution of time, now basically use only two of these, Interested can refer to my previous blog in the HTTP protocol get and post, the iOS client needs to deal with the server, get and post is not able to run, this article contains iOS code and a small number of Java server code, get started.

get and post sync requests

Get and post synchronization requests the most common is the login, enter a variety of passwords to see the function, must be synchronous, asynchronous on the web when the local refresh with more, more time-consuming time to execute asynchronous requests, you can let customers see a part of the function, and then slowly refresh, For example, when a restaurant eats more than 10 dishes, give you one or two to eat first, then to others, the rest slowly. That's probably it. Get a few buttons first:

Paste the code for the sync request first:

     Set URL path     nsstring *urlstr=[nsstring stringwithformat:@ "http://localhost:8080/myweb/book?username=%@& Password=%@&type=get ", @" blog Park ", @" Keso "];     Urlstr=[urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];     Nsurl *url=[nsurl Urlwithstring:urlstr];        Set network request via URL    nsurlrequest *request = [[Nsurlrequest alloc]initwithurl:url CachePolicy: Nsurlrequestuseprotocolcachepolicy Timeoutinterval:10];    Nserror *error=nil;    Get Server data    nsdata *requestdata= [nsurlconnection sendsynchronousrequest:request returningresponse:nil Error: &error];    if (err) {        NSLog (@ "error message:%@", [Error localizeddescription]);    } else{        nsstring *result=[[nsstring alloc]initwithdata:requestdata encoding:nsutf8stringencoding];        NSLog (@ "return result:%@", result);    }

There is a lot of code to explain:

①url If there is no Chinese to pass, you need to encode:

[Urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];

② set the code in the network request, there are two parameters, the last time to set the request, this needless to say, the focus of the cache policy CachePolicy, the system is defined as follows:

typedef ns_enum (Nsuinteger, nsurlrequestcachepolicy) {    nsurlrequestuseprotocolcachepolicy = 0,    Nsurlrequestreloadignoringlocalcachedata = 1,    nsurlrequestreloadignoringlocalandremotecachedata = 4,// unimplemented    nsurlrequestreloadignoringcachedata = Nsurlrequestreloadignoringlocalcachedata,    Nsurlrequestreturncachedataelseload = 2,    nsurlrequestreturncachedatadontload = 3,    Nsurlrequestreloadrevalidatingcachedata = 5,//unimplemented};

Nsurlrequestuseprotocolcachepolicy (Basic strategy), nsurlrequestreloadignoringlocalcachedata(ignoring local cache);

Nsurlrequestreloadignoringlocalandremotecachedata(ignoring any cache policy, whether local or remote, always re-downloaded from the original address);

Nsurlrequestreturncachedataelseload (First use the cache, if there is no local cache, only download from the original address);

Nsurlrequestreturncachedatadontload (use local cache, never download, if there is no cache locally, the request fails, this policy is used for offline operation);

Nsurlrequestreloadrevalidatingcachedata (if the local cache is valid, do not download, and any other cases are re-downloaded from the original address);

Java Service-side code:

protected void doget (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {// TODO auto-generated Method Stubresponse.setcontenttype ("TEXT/HTML;CHARSET=UTF-8;"); PrintWriter out = Response.getwriter (); System.out.println (Request.getparameter ("username")); System.out.println (Request.getparameter ("password")), if (Request.getparameter ("type") = = null) {out.print ("Default Test");} else {if (Request.getparameter ("type"). Equals ("async")) {Out.print ("Asynchronous Get Request");} else {out.print ("GET Request");}}

The final effect is as follows:

The code for the POST request, basically with the get type, has comments, not much to explain:

   Set URL    nsurl *url=[nsurl urlwithstring:@ "Http://localhost:8080/MyWeb/Book"];    Create request    Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc]initwithurl:url CachePolicy: Nsurlrequestuseprotocolcachepolicy Timeoutinterval:10];        [Request sethttpmethod:@ "POST"];//settings requested by post, default to get        nsstring *param= @ "name= Blog Park &address=http:// Www.cnblogs.com/xiaofeixiang&Type=post ";//Set parameter        nsdata *data = [param datausingencoding: Nsutf8stringencoding];        [Request Sethttpbody:data];        Connection Server    NSData *received = [nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil];    NSString *result= [[NSString alloc]initwithdata:received encoding:nsutf8stringencoding];    NSLog (@ "%@", result);

Java Service-side code:

protected void DoPost (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException {/ /TODO auto-generated method stubrequest.setcharacterencoding ("Utf-8");  Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); System.out.println ("Name:" + request.getparameter ("name")); SYSTEM.OUT.PRINTLN ("Address:" + request.getparameter ("adress")); SYSTEM.OUT.PRINTLN ("Types:" + request.getparameter ("type")), if (Request.getparameter ("type"). Equals ("async")) { Out.print ("Asynchronous Request");} else {out.print ("POST request");}}

The effect is as follows:

get and post asynchronous requests

asynchronous implementations require protocol implementation nsurlconnectiondatadelegate,get async code is as follows:

   Set URL path    nsstring *urlstr=[nsstring stringwithformat:@ "http://localhost:8080/myweb/book?username=%@& Password=%s&type=async ", @" Flyelephant "," Keso "];       Urlstr=[urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];        Nsurl *url=[nsurl Urlwithstring:urlstr];    Create request    Nsurlrequest *request = [[Nsurlrequest alloc]initwithurl:url CachePolicy: Nsurlrequestuseprotocolcachepolicy Timeoutinterval:10];        Connection Server    nsurlconnection *connection = [[Nsurlconnection alloc]initwithrequest:request delegate:self];

Ways to implement the Protocol's connection process:

-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{    Nshttpurlresponse *res = (Nshttpurlresponse *) response;        NSLog (@ "%@", [res allheaderfields]);        Self.myresult = [Nsmutabledata data];} Called when the server transmits data, this method executes several times according to the data size-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{    [Self.myresult appenddata:data];    } Execution method After data transfer is complete-(void) connectiondidfinishloading: (nsurlconnection *) connection{    nsstring *receivestr = [[ NSString Alloc]initwithdata:self.myresult encoding:nsutf8stringencoding];        NSLog (@ "%@", receivestr);    } Network request error (Network off, Connection timeout) execution method-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{    NSLog (@ "%@", [Error localizeddescription]);}

The asynchronous transfer process data needs to be spliced, so this time you need to set a property to receive data:

@property (strong,nonatomic) Nsmutabledata *myresult;

The effect is as follows:

Post Asynchronous pass code:

   Set URL    nsurl *url=[nsurl urlwithstring:@ "Http://localhost:8080/MyWeb/Book"];        Set Request    Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc]initwithurl:url CachePolicy: Nsurlrequestuseprotocolcachepolicy Timeoutinterval:10];        [Request sethttpmethod:@ "POST"];//settings requested by post, default to get        nsstring *param= @ "name=keso&address=http:// Www.cnblogs.com/xiaofeixiang&Type=async ";//Set parameter        nsdata *data = [param datausingencoding: Nsutf8stringencoding];        [Request Sethttpbody:data];    Connection Server    nsurlconnection *connection = [[Nsurlconnection alloc]initwithrequest:request delegate:self];

The effect is as follows:

Asynchronous requests are relatively simple, the required methods are already encapsulated, it is important to note that the data is dynamically spliced, the requested code is implemented in the Java servlet, the directory in the Java project is as follows:

book.java in code as follows:

Import Java.io.ioexception;import java.io.printwriter;import Java.net.urldecoder;import Java.net.URLEncoder;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;/** * servlet Implementation Class Book */@WebServlet ("/book") public class book extends HttpServlet {private static final long Serialver Sionuid = 1l;/** * @see httpservlet#httpservlet () */public book () {super ();//TODO auto-generated Constructor stub}/** * @ See Httpservlet#doget (HttpServletRequest request, HttpServletResponse * response) */protected void Doget (HTTPSERVLETR Equest request,httpservletresponse response) throws Servletexception, IOException {//TODO auto-generated method Stubresponse.setcontenttype ("TEXT/HTML;CHARSET=UTF-8;"); PrintWriter out = Response.getwriter (); System.out.println (Request.getparameter ("username")); System.out.println (Request.getparameter ("Password ")), if (Request.getparameter (" type ") = = null) {out.print (" Default Test "),} else {if (Request.getparameter (" type "). Equals ("Async")) {Out.print ("Asynchronous Get Request");} else {out.print ("GET Request");}}} /** * @see Httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) */protected void DoPost (HTT Pservletrequest request,httpservletresponse response) throws Servletexception, IOException {//TODO auto-generated  Method Stubrequest.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Text/html;charset=utf-8"); PrintWriter out = Response.getwriter (); System.out.println ("Name:" + request.getparameter ("name")); SYSTEM.OUT.PRINTLN ("Address:" + request.getparameter ("adress")); SYSTEM.OUT.PRINTLN ("Types:" + request.getparameter ("type")), if (Request.getparameter ("type"). Equals ("async")) { Out.print ("Asynchronous post Request");} else {out.print ("POST request");}}}
Get and Post summary

Once the ① synchronization request is sent, the program will stop the user interaction until the server returns data to complete before proceeding to the next step (for example, login verification);

② asynchronous requests do not block the main thread, a new thread is created to operate, the UI can still be manipulated after an asynchronous request is made, and the program can continue to run;

③get request, the parameters are written directly on the access path, easy to be seen by the outside, security is not high, address up to 255 bytes;

④post request, put the parameters into the body inside, high security, not easy to capture;

iOS Development-get requests, post requests, synchronous requests, and asynchronous requests

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.