iOS development uses nsurlconnection, Nsurlsession, AFN, ASI Four ways to implement HTTP requests

Source: Internet
Author: User

Summary: HTTP requests can be implemented using Nsurlconnection, Nsurlsession, AFN, ASI and other methods, including GET, post two request mode and synchronous, asynchronous program execution mode.

Nsurlconnection

1 Get-Mode synchronization requests

/**

 *  get sync request

 */

-(void) getsynch{

    //  get URL

    nsurl *url = [[nsurl alloc]  initwithstring:@ "http://localhost:8070/MJServer/login?username=123&password=123"];

    //  GET request requests

    nsurlrequest *request = [Nsurlrequest requestwithurl:url];

    

    

    //  send synchronization requests

    nsdata *data = [nsurlconnection sendsynchronousrequest:request  Returningresponse:nil error:nil];

    

    //  convert data to string

    nsstring *result = [[nsstring alloc] initwithdata:data encoding: Nsutf8stringencoding];

    

    nslog (@ "Data-%@", result);

}

 

2 asynchronous request with Get mode

/**

* Get Asynchronous request

*/

-(void) getasynch{

Get URL

Nsurl *url = [[Nsurl alloc] initwithstring:@ "Http://localhost:8070/MJServer/video"];

GET request Requests

Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];

Send a sync request

[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {

Turn data into a dictionary

Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];

NSLog (@ "Data-%@", dict);

}];

}

3 post Sync request

/**

* Post Sync Request

*/

-(void) postsynch{

Get URL

Nsurl *url = [[Nsurl alloc] initwithstring:@ "Http://localhost:8070/MJServer"];

Setting up a POST request requires the use of nsmutableurlrequest

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

Set the request mode to post (required)

Request. HttpMethod = @ "POST";

Send a sync request

NSData *data = [nsurlconnection sendsynchronousrequest:request returningresponse:nil Error:nil];

Convert data to String

NSString *result = [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding];

NSLog (@ "Data-%@", result);

}

4 post Asynchronous request

/**

* Post Asynchronous request

*/

-(void) postasynch{

Get URL

Nsurl *url = [[Nsurl alloc] initwithstring:@ "Http://localhost:8070/MJServer/login"];

GET request Requests

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

Set the request mode to post

Request. HttpMethod = @ "POST";

Set form parameters (optional)

NSString *params = [NSString stringwithformat:@ "username=123&pwd=123"];

Request. Httpbody = [params datausingencoding:nsutf8stringencoding];

Set timeout (optional)

Request.timeoutinterval = 5;

Set Request header information (optional)

[Request setvalue:@ "IPhone 6" forhttpheaderfield:@ "User-agent"];

Setting up a POST request requires the use of nsmutableurlrequest

[Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {

Turn data into a dictionary

Nsdictionary *dict = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];

NSLog (@ "Data-%@", dict);

}];

}

Nsurlsession

1 GET Request for session

/**

 *  session GET request

 */

-(void) sessionget{

    //  Get a session instance

    NSURLSession  *session = [Nsurlsession sharedsession];

    

    //  Get URL

    nsurl *url = [[nsurl alloc] initwithstring:@] http://localhost:8070/MJServer/ Video "];

    //  Create a data Access task

    nsurlsessiondatatask *task = [Session datataskwithurl:url completionhandler : ^ (nsdata *data, nsurlresponse *response, nserror *error) {

        nslog (@ "Data--%@", [[nsstring alloc] initwithdata:data encoding:nsutf8stringencoding ]);

   }];

    //  start tasks, start, reply with resume

    [task resume];

}

2 POST request for session

/**

* POST request for session

*/

-(void) sessionpost{

Get a Session instance

Nsurlsession *session = [Nsurlsession sharedsession];

Get URL

Nsurl *url = [[Nsurl alloc] initwithstring:@ "Http://localhost:8070/MJServer/login"];

Get the Request requests object

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

Set Request mode

Request. HttpMethod = @ "POST";

Set the request body,

NSString *params = @ "username=123&pwd=123";

Request. Httpbody = [params datausingencoding:nsutf8stringencoding];

Create a data Access task

Nsurlsessiondatatask *task = [Session datataskwithrequest:request completionhandler:^ (NSData *data, NSURLResponse * Response, Nserror *error) {

NSLog (@ "Data-%@", [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]);

}];

Start Task

[Task resume];

}

Afnetwork Framework, need to import #import "AFNetworking.h"

1 Get Request for AFN

#import "AFNetworking.h"

/**

* AFN GET request

*/

-(void) afnget{

Create a Request Operations Manager

Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager];

Declaration response results are not parsed in JSON, XML, etc., and return data directly

Manager.responseserializer = [Afhttpresponseserializer serializer];

Set request parameters (optional)

Nsmutabledictionary *params = [Nsmutabledictionary dictionary];

params[@ "username"] = @ "123";

params[@ "pwd"] = @ "123";

Send a GET request

NSString *url = @ "Http://localhost:8070/MJServer/login";

[Manager Get:url Parameters:params success:^ (afhttprequestoperation *operation, id responseobject) {

The request was successfully processed here

Convert response data into a dictionary

Nsdictionary *dict = [Nsjsonserialization jsonobjectwithdata:responseobject options:nsjsonreadingallowfragments Error:nil];

NSLog (@ "%@", dict);

} failure:^ (Afhttprequestoperation *operation, Nserror *error) {

If the request fails to process here

NSLog (@ "request fail");

}];

}

2 AFN POST Request

/**

* AFN's POST request

*/

-(void) afnpost{

Create a Request Operations Manager

Afhttprequestoperationmanager *manager = [Afhttprequestoperationmanager manager];

Declaration response results are not parsed in JSON, XML, etc., and return data directly

Manager.responseserializer = [Afhttpresponseserializer serializer];

Set request parameters (optional)

Nsmutabledictionary *params = [Nsmutabledictionary dictionary];

params[@ "username"] = @ "123";

params[@ "pwd"] = @ "123";

Send a GET request

NSString *url = @ "Http://localhost:8070/MJServer/login";

[Manager Post:url Parameters:params success:^ (afhttprequestoperation *operation, id responseobject) {

The request was successfully processed here

Convert response data into a dictionary

Nsdictionary *dict = [Nsjsonserialization jsonobjectwithdata:responseobject options:nsjsonreadingallowfragments Error:nil];

NSLog (@ "%@", dict);

} failure:^ (Afhttprequestoperation *operation, Nserror *error) {

If the request fails to process here

NSLog (@ "request fail");

}];

}

ASI (Note Adding the Libz class Library and modifying the ASI source file to be non-arc)

1 ASI Get sync request

#import "ASIHTTPRequest.h"

/**

* ASI's Get sync request

*/

-(void) asigetsynch{

Get URL

Nsurl *url = [[Nsurl alloc] initwithstring:@ "Http://localhost:8070/MJServer/video"];

Get ASI Request Object

ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];

Send a sync request

[Request startsynchronous];

Nserror *error = [request ERROR];

if (Error) {

NSLog (@ "request failed");

}else{

NSString *data = [request responsestring];

NSData *data = [request ResponseData];

Nsdictionary *result = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil];

NSLog (@ "Result-%@", result);

}

}

2 Get asynchronous request for ASI

/**

* ASI's Get asynchronous request

* Note: The ASI monitoring request process is delegate, block and selector three ways,

* The test found that delegate and block can be executed simultaneously, selector and block can be executed simultaneously, but delegate and selector coexist (including three coexistence) do not perform delegate

* Execution order: Delegate > Selector > block

* Data not available through ResponseData and responsestring

* You cannot get data directly from ResponseData and responsestring using a proxy

*/

-(void) asigetasynch{

Get URL

Nsurl *url = [[Nsurl alloc] initwithstring:@ "Http://localhost:8070/MJServer/video"];

Get ASI Request Object

ASIHTTPRequest *request = [ASIHTTPRequest Requestwithurl:url];

Set up the Asihttprequestdelegate agent.

Request.delegate = self;

Sending an asynchronous request

[Request startasynchronous];

Block to set the listening request process

[Request setstartedblock:^{

NSLog (@ "block request Start");

}];

[Request setdatareceivedblock:^ (NSData *data) {

NSLog (@ "Block gets request data--%@", [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error: Nil]);

}];

[Request setcompletionblock:^{

NSLog (@ "block request End");

}];

Set the selector of the listener request process

[Request Setdidstartselector: @selector (start:)];

[Request Setdidreceivedataselector: @selector (receivedata:)];

[Request Setdidfinishselector: @selector (finish:)];

}

#pragma mark Selector Monitoring method

-(void) Start: (ASIHTTPRequest *) request{

NSLog (@ "selector request start");

}

-(void) Receivedata: (ASIHTTPRequest *) request{

The data is not available here

NSLog (@ "Selector obtain request data-%@", [request responsestring]);

}

-(void) Finish: (ASIHTTPRequest *) request{

NSLog (@ "selector request End");

}

#pragma mark implements the proxy method for Asihttprequestdelegate

-(void) Request: (ASIHTTPRequest *) Request Didreceivedata: (NSData *) data{

NSLog (@ "Delegate GET request data-%@", [Nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil]);

}

-(void) requeststarted: (ASIHTTPRequest *) request{

NSLog (@ "Delegate request start");

}

-(void) requestfinished: (ASIHTTPRequest *) request{

NSLog (@ "Delegate request End");

}

-(void) requestfailed: (ASIHTTPRequest *) request{

NSLog (@ "Delegate request failed");

}

3 ASI Post Asynchronous request

#import "ASIFormDataRequest.h"

/**

* ASI Post Asynchronous request

*/

-(void) asipostasynch{

Get URL

Nsurl *url = [[Nsurl alloc] initwithstring:@ "Http://localhost:8070/MJServer/login"];

Get ASI Form Request Object

Asiformdatarequest *request = [Asiformdatarequest Requestwithurl:url];

Set Request parameters

[Request setpostvalue:@ "123" forkey:@ "username"];

[Request setpostvalue:@ "123" forkey:@ "pwd"];

You can't get data directly from ResponseData and responsestring using proxies

Request.delegate = self;

Sending an asynchronous request

[Request startasynchronous];

Set the listener (only the Block method is shown here)

__weak asiformdatarequest *req = Request;

[Request setcompletionblock:^{

NSLog (@ "selector GET request data-%@", [req responsestring]);

}];

}

iOS development uses nsurlconnection, Nsurlsession, AFN, ASI Four ways to implement HTTP requests

Related Article

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.