ios-Network Requests

Source: Internet
Author: User

Network requests include get.post two ways, with the steps:1> get the URL. 2> gets the request. 3> Create a link. 4> returns data (proxy).

1> gets the URL.

NSString *[email protected] "HTTP://API.ZBW.VC/API/VIP/GETPHONEPADTAGMSG";//When the parameter is Chinese, UTF8 code//URLSTR=[URLSTR Stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]; Nsurl *url=[nsurl URLWITHSTRING:URLSTR];

2> gets the request.

Nsurlrequest *request=[nsurlrequest Requestwithurl:url];

The parameters of the default Get method require only URL stitching.

When creating the Post method, do the following for the request

<span style= "FONT-SIZE:18PX;" >nsstring *datastr=[nsstring stringwithformat:@ "username=%@&loginpwd=%@", self. Qqfield.text,self.pwdfield.text]; NSData *data=[datastr datausingencoding:nsutf8stringencoding]; [Request Sethttpbody:data]; [Request sethttpmethod:@ "POST"]; [Request settimeoutinterval:5.0];</span>

3> Create a link.

at this point, the proxy is created for this class, so the class must inherit the protocol < nsurlconnectiondatadelegate >

Nsurlconnection *conn=[nsurlconnection connectionwithrequest:request delegate:self];

4> returns data (proxy). Implementing a proxy must implement the following methods

<span style= "FONT-SIZE:18PX;" >//Network return data Start-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response//repeat call, Return data processing-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data//return end-(void) Connectiondidfinishloading: (nsurlconnection *) connection//error handling Method-(void) connection: (Nsurlconnection *) Connection didfailwitherror: (Nserror *) error</span>


iOS provides another way to implement data backhaul

1. Sync >>

NSData *data=[nsurlconnection sendsynchronousrequest:request Returningresponse:&resp error:&error];

2. Asynchronous >>

[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ (block)];


The specific code is as follows:

<span style= "color: #333333;" > #import "CSZViewController.h" @interface Cszviewcontroller () @property (nonatomic,strong) Nsmutabledata * Mutabledata; @end @implementation cszviewcontroller-(void) viewdidload{[super Viewdidload];}    -(Nsurlrequest *) getrequest {nsstring *[email protected] "HTTP://API.ZBW.VC/API/VIP/GETPHONEPADTAGMSG";    When the parameter is Chinese, use UTF8 code//urlstr=[urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];        Nsurl *url=[nsurl URLWITHSTRING:URLSTR];    Nsurlrequest *request=[nsurlrequest Requestwithurl:url]; return request;}    -(Ibaction) getlogin {nsurlrequest *request = [self getrequest];    Nsurlconnection *conn=[nsurlconnection connectionwithrequest:request delegate:self]; [conn start];} -(Nsmutableurlrequest *) getasyncrequest {nsstring *[email protected] "Http://api.zbw.vc/api/Vip/PostUserInfo"    ;    Nsurl *url=[nsurl URLWITHSTRING:URLSTR];      Nsmutableurlrequest *request=[nsmutableurlrequest Requestwithurl:url];  NSString *datastr=[nsstring stringwithformat:@ "username=%@&loginpwd=%@", self.        Qqfield.text,self.pwdfield.text];        NSData *data=[datastr datausingencoding:nsutf8stringencoding];    [Request Sethttpbody:data];    [Request sethttpmethod:@ "POST"];    [Request settimeoutinterval:5.0]; return request;}        -(Ibaction) postlogin {[UIApplication sharedapplication].networkactivityindicatorvisible=yes;    Nsmutableurlrequest *request = [self getasyncrequest];    Nsurlconnection *conn=[nsurlconnection connectionwithrequest:request delegate:self]; [conn start];} -(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{NSLog (@ "%@", @ " Network return data start "); -(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{if (_mutabledata==nil) {_mutable    Data=[nsmutabledata data]; } [_mutabledata appenddata:data];} -(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{_mutabledata=nil;} -(void) Connectiondidfinishloading: (nsurlconnection *) connection{nsstring *str=[[nsstring alloc] InitWithData:_    Mutabledata encoding:nsutf8stringencoding];        NSLog (@ "%@", str);    if (_mutabledata!=nil) {_mutabledata=nil; } [UIApplication Sharedapplication].networkactivityindicatorvisible=no;}    -(Ibaction) Clicksync {nsurlrequest *request = [self getrequest];    Nsurlresponse *resp=nil;    Nserror *error=nil;    NSData *data=[nsurlconnection sendsynchronousrequest:request Returningresponse:&resp error:&error];        if (Error!=nil) {NSLog (@ "%@", error.localizeddescription);    Return } if (Data!=nil) {//decode NSString *respstr=[[nsstring alloc] Initwithdata:data Encoding:nsutf8stringen        Coding];    NSLog (@ "%@", respstr);    } else {NSLog (@ "Cannot get network data");        }}-(Ibaction) clickasync {nsurlrequest *request = [self getasyncrequest]; [Nsurlconnection sendasynchronousrequest:request Queue:[nsoperationqueuE Mainqueue] completionhandler:^ (nsurlresponse *response, NSData *data, Nserror *connectionerror) {if (ConnectionE        Rror!=nil) {NSLog (@ "%@", connectionerror.localizeddescription); }else if (response!=nil) {//decode NSString *res=[[nsstring alloc] Initwithdata:data encoding:nsutf8str            Ingencoding];        NSLog (@ "%@", res);        }else{NSLog (@ "Access to network data");        }    }]; } @end </span>

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.