ios-Network (GET request and POST request, HTTP communication process, request timeout, url transcoding)

Source: Internet
Author: User

1 //2 //VIEWCONTROLLER.M3 //ios_0129_http Request4 //5 //Created by Ma C on 16/1/29.6 //copyright©2016 Blog Technology. All rights reserved.7 //8 9 #import "ViewController.h"Ten #import "mbprogresshud+mj.h" One  A @interfaceViewcontroller () -@property (Weak, nonatomic) Iboutlet Uitextfield *Textname; -@property (Weak, nonatomic) Iboutlet Uitextfield *Textpassword; the  --(ibaction) btnlogin; -  - @end +  - @implementationViewcontroller +  A /* at   - 1. Methods for sending HTTP requests - 1> defines 8 ways to send HTTP requests in the HTTP/1.1 protocol - Get,post,options,head,put,delete,trace,connect,patch - 2> According to the HTTP protocol design, different methods of resources have different ways of Operation - PUT: Increase in Delete: Delete - POST: Change to GET: Check + 3> most commonly used is the get,post (in fact Get,post can do to delete and change) - 4> Parameters-specific data passed to the server the   * 2.GET and post comparison $ 1>get and Post are mainly embodied in the data transmissionPanax Notoginseng a.get The parameter sent to the server after the request URL, with & separated by multiple parameters - the parameters behind the B.url cannot exceed 1KB the   + c.post The parameters sent to the server are all placed in the request body A d. Theoretically, there is no limit to the amount of data delivered by post (see Server processing Power) the   + 3.GET and post selection - 1> Pass large amounts of data only with post (file upload) $ 2>get security is worse than post, confidential information with post $ 3> is simply to request data (data query) with Get - 4> If it is to delete and change the data, it is recommended to use post -   the 4.HTTP Communication Process-Request - The 1>http protocol stipulates that a complete HTTP request sent by the client to the server contains the following contentWuyi A. Request line: Contains the request method, the request resource path, the HTTP version protocol the B. Request header: Contains the environment description of the client, the host address of the client request, etc. - Host : The address of the server that the client wants to access Wu user-agent: Client type, client-side software Environment - Accept: The type of data that the client can receive About Accept-language: The language environment of the client $ accept-encoding: The data compression format supported by the client - c. Request body: Specific data sent by the client to the server -   - 5.HTTP Communication Process-response A 1> The client sends a request to the server, the server should respond by returning the data to the client + The 2>http protocol stipulates that a complete HTTP response should contain the following content the A. Status line: Contains the HTTP protocol version, status code, status English name - B. Response header: Contains a description of the server, a description of the returned data $ Server : Types of servers the Content-type: The data type returned the Content-length: The length of the returned data the Date: Time of response the 3> Entity content: Specific data returned by the server to the client - 4> Common response status codes: in  */ the  the- (void) Viewdidload { About [Super Viewdidload]; the      theSelf.view.backgroundColor =[Uicolor Grouptableviewbackgroundcolor]; the } +  -- (void) Touchesbegan: (Nsset<uitouch *> *) touches withevent: (Uievent *)Event the {Bayi [Self.view Endediting:yes]; the } the  --(ibaction) btnlogin { -      theNSString *usernametext =Self.textName.text; the     if(Usernametext.length = =0) { the[Mbprogresshud ShowError:@"Please enter your account number"]; the         return; -     } theSelf.textPassword.secureTextEntry =YES; theNSString *password =Self.textPassword.text; the     if(Password.length = =0) {94[Mbprogresshud ShowError:@"Please enter your password"]; the         return; the     } the     //1.GET Request Default98 //    //Create a Nsurl: request path About //nsstring *strurl = [NSString stringwithformat:@]http://localhost: 8080/mjserver/login?username=%@&pwd=%@ ", Usernametext,password]; -     101 //    //Nsurl can not contain Chinese, you have to transcode the Chinese102 //strURL = [strURL stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];103     104 //Nsurl *url = [Nsurl Urlwithstring:strurl]; the //    //Create a request106 //nsurlrequest *request = [Nsurlrequest requestwithurl:url];107     108     //Add Mask109[Mbprogresshud ShowMessage:@"being desperately loading ..."]; the     111     //2.POST Request theNSString *strurl =@"Http://localhost:8080/MJServer/login";113Nsurl *url =[Nsurl Urlwithstring:strurl]; theNsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; the      the     //Request Timeout after 5s (default 60s timeout)117Request.timeoutinterval =5;118     //Set Request Mode119Request. HttpMethod =@"POST"; -     //set the request header121[Request SetValue:@"IPhone6"Forhttpheaderfield:@"user-agent"];122     123     //set the request body124NSString *param = [NSString stringWithFormat:@"username=%@&pwd=%@", Usernametext,password]; the     //NSString-NSData126Request. Httpbody =[param datausingencoding:nsutf8stringencoding];127      -     //Asynchronous Request129 [self sendasyncwithrequest:request]; the     131 } the //Asynchronous Request133- (void) Sendasyncwithrequest: (Nsurlrequest *) Request134 {135Nsoperationqueue *queue =[Nsoperationqueue Mainqueue];136     137[Nsurlconnection sendasynchronousrequest:request queue:queue completionhandler:^ (NSURLResponse * _Nullable response, NSData * _nullable data, Nserror *_nullable Connectionerror) {138         139         //Hide Masks $ [Mbprogresshud Hidehud];141Nshttpurlresponse *RESP = (Nshttpurlresponse *) response;142NSString *msg =[Nshttpurlresponse LocalizedStringForStatusCode:resp.statusCode];143NSLog (@"%ld%@%@", Resp.statuscode, MSG, resp.allheaderfields);144         145         //this block will be automatically called when the request is complete.146         if(Connectionerror | | data = =Nil) {147[Mbprogresshud ShowError:@"request failed"];148             return;149         } Max         //parse the JSON data returned by the server151Nsdictionary *dict =[nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaves Error:nil]; theNSString *error = dict[@"Error"];153         if(Error) {154 [Mbprogresshud Showerror:error];155         }156         Else{157NSString *success = dict[@"Success"];158 [Mbprogresshud showsuccess:success];159         } the     }];161 }162 163 @end

ios-Network (GET request and POST request, HTTP communication process, request timeout, url transcoding)

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.