Nsurlsession Accessing network data

Source: Internet
Author: User

Settings for 1.NSMutableURLRequest

Create a Nsmutableurlrequest object

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

Set Request type

[Request Sethttpmethod:@ "POST"];

Setting the time-out period

[Request Settimeoutinterval:];

Set Cache Policy

[Request Setcachepolicy:nsurlrequestreloadignoringcachedata];

Set up BASE64 Certification

NSString *authstring = [[[NSString stringWithFormat:@ '%@:%@', KGlobal.userInfo.sAccount, KGlobal.userInfo.sPassword] datausingencoding:nsutf8stringencoding] base64encodedstringwithoptions:0  @ "Basic%@", authstring]; [Request setvalue:authstring Forhttpheaderfield: @" Authorization "];

Set the parameters that the Post method needs to pass

NSString *paramstr = [NSString stringWithFormat:@ "postid=%@&name=%@&text=%@"  *bodydata = [Paramstr datausingencoding:nsutf8stringencoding];[ Request Sethttpbody:bodydata];
2. Create a network session

Create a network session

Nsurlsession *session = [Nsurlsession sharedsession];
3. Create a network request (this article describes the Nsurlsessiondatatask and nsurlsessionuploadtask two types)

Scenario One: Using Nsurlsessiondatatask to request network data

Nsurlsessiondatatask *task = [Session datataskwithrequest:request completionhandler:^ (NSData * _Nullable data, Nsurlresponse * _nullable response, Nserror *_nullable Error) {        if(Error = =Nil) {NSLog (@"text published successfully!"); Nshttpurlresponse*httpresponse = (Nshttpurlresponse *response;//The Response object to Nshttpurlresponse, you can get header information for the HTTP response message, such as response code 200, which indicates that the request was successful (Httpresponse.statuscode gets ) NSLog (@"returns the response:%@", HttpResponse); Nserror*error =Nil;
The body content of the real HTTP response needs to be serialized to get Nsdictionary
*dic = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutableleaveserror:&error];//Returns a dictionary type data
Nsarray *array = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingmutablecontainers error:&error];//returns a JSON array
Nsarray *array = [nsjsonserialization jsonobjectwithdata:[[dic valueforkey:@ "Pictures"] datausingencoding: Nsutf8stringencoding] Options:nsjsonreadingmutablecontainers error:&error];//
[DiC valueforkey:@ "Pictures"] get the first parse of the JSON array string, need two times to parse into a JSON array      
if (! error) {                NSLog (@ " return information:%@", DIC);            }        } Else {            NSLog (@ " publish failed, code%@", error);        }
}];
4. Send a network request
[Task resume];

Scenario two: Using Nsurlsessionuploadtask to request network data, Nsurlsessionuploadtask and The difference between nsurlsessiondatatask is that Nsurlsessionuploadtask is more like a Web form submission, such as an image upload that simulates a Web form can use Nsurlsessionuploadtask.

Nsurlsessionuploadtask *datatask = [Session uploadtaskwithrequest:request Fromdata:bodydata completionHandler:^ ( NSData * _nullable data, Nsurlresponse * _nullable response, Nserror *_nullable Error) {if(Error = =Nil) {NSLog (@"Publish successfully!"); Nshttpurlresponse*httpresponse = (Nshttpurlresponse *) response; NSLog (@"Statuscode:%lu", Httpresponse.statuscode); NSLog (@"%@", [[NSString alloc] Initwithdata:data encoding:nsutf8stringencoding]); if(Picnum = =self.imgsArray.count) {[Svprogresshud showsuccesswithstatus:ktxt (@"imuploadsuccess")];            [Self dismissviewcontrolleranimated:yes completion:nil]; }        }Else{NSLog (@"Publish failed, code%@!", error); }
}];

The method and method of sending network request above is the difference of bodydata construction, method two Bodydata is to simulate the message structure of HTTP, use NSData to splice HTTP message.

The construction method of Bodydata

-(NSData *) Getbodydatawithimage: (UIImage *) image{//convert the file to NSDataNSData *filedata = uiimagejpegrepresentation (image,1.0); NSString*filename=[Global Getuniquestrbyuuid]; //1. Construct Body StringNsmutablestring *bodystring =[[Nsmutablestring alloc] init]; //2. Stitching the body string//(1) file_name[Bodystring AppendFormat:@"--%@\r\n", Boundry]; [Bodystring AppendFormat:@"content-disposition:form-data; name=\"Filename\"\ r \ n"]; [Bodystring AppendFormat:@"Content-type:text/plain; charset=\"utf-8\"\r\n\r\n"]; [Bodystring AppendFormat:@"aaa%@.jpg\r\n", FileName]; //(2) PostID[Bodystring AppendFormat:@"--%@\r\n", Boundry]; [Bodystring AppendFormat:@"content-disposition:form-data; name=\"Postid\"\ r \ n"]; [Bodystring AppendFormat:@"Content-type:text/plain; charset=\"utf-8\"\r\n\r\n"]; [Bodystring AppendFormat:@"%@\r\n", Self.uuid]; //(3) pic[Bodystring AppendFormat:@"--%@\r\n", Boundry]; [Bodystring AppendFormat:@"content-disposition:form-data; name=\"Pic\"; filename=\ "%@.jpg\" \ r \ n", FileName]; [Bodystring AppendFormat:@"content-type:image/jpeg\r\n\r\n"]; //[bodystring appendformat:@ "content-type:application/octet-stream\r\n\r\n"]; //3.string --DataNsmutabledata *bodydata =[Nsmutabledata data]; //the process of splicing//previous bodystring, other parameters[Bodydata appenddata:[bodystring datausingencoding:nsutf8stringencoding]; //Picture Data[Bodydata Appenddata:filedata]; //4. End of separator lineNSString *endstr = [NSString stringWithFormat:@"\r\n--%@--\r\n", Boundry]; //stitching to the last side of the Bodydata[Bodydata appenddata:[endstr datausingencoding:nsutf8stringencoding]; returnBodydata;}

The entire Bodydata construction process principle according to the HTTP message uploads the picture, the format uses the boundory to divide, but each time the HTTP message boundory value is not the same, here in order to conveniently define a fixed value, in fact fixed value also can upload success, pro-test effective. HTTP body inside the text and picture content with boundory and newline characters to split, Partition sent, mail content is similar, so long as the HTTP message format, you can simulate HTTP message upload image.

Settings for Boundry

Static @" ----------V2ymhfg03ehbqgzcako6jy "; // Set Boundaries

[Global Getuniquestrbyuuid] is a tool class method used to generate a GUID, detailed by the following details:

+ (NSString *) getuniquestrbyuuid{    cfuuidref    = cfuuidcreate (nil);   Create a new UUID        //Get the string representation of the UUID        nsstring< c10/>*uuidstring = (__bridge_transfer NSString *) cfuuidcreatestring (nil, uuidobj);        Cfrelease (uuidobj);         return uuidstring;}

Instance Code

Nsurlsession Accessing network data

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.