Get request sent by session, POST request, upload, download

Source: Internet
Author: User
Tags allkeys html header

http Method: The difference between a GET request and a POST requestGet is a request to send data to the server, and post is a request to submit data to the server get is to get information, not modify information, like database query function, the data will not be modified The parameters of the GET request are passed after the URL, the requested data is appended to the URL, the URL is split, the data is transferred, and the parameters are connected & XX in%xx is the ASCII of the symbol in 16 notation, if the data is an English letter/number, sent as is, if it is a space, converted to +, if it is Chinese/other characters, the string is directly encrypted with BASE64. The data for a get transfer has a size limit, because get is submitting data through a URL, so the amount of data that get can commit is directly related to the length of the URL, and different browsers have different limits on the length of the URL. Get request data will be cached by the browser, the user name and password will appear in plaintext on the URL, others can find historical browsing records, the data is not very safe. On the server side, use Request.QueryString to get the data submitted by the Get methodThe POST request is sent to the Web server as the actual content of the HTTP message, and the data is placed within the HTML header for submission, post does not limit the data that is submitted. Post is safer than get, when the data is in Chinese or not sensitive data, then with GET, because using GET, parameters will be displayed in the address, for sensitive data and not Chinese characters of data, then use PostPost to represent the possibility of modifying resources on the server, on the server side, Data submitted by post can only be obtained using Request.Form. a GET request for a GET request parameters are passed after the URL, the requested data will be appended to the URL, to split the URL and transfer data, the parameters are connected with & 1. Request Address URL Nsurl *url = [Nsurl urlwithstring:urlstring];
2. Gets the delimiter between the absolute path and the parameter string. Determine if the URL has parameters, if the parameter exists, then fill @ "&" nsstring *str = [email protected] "&": @ "?"; Get the argument string paramsstring (dictionary converted to string, according to the condition, the step can be omitted) nsmutablestring *paramsstring = [[Nsmutablestring alloc] init];
For (NSString *key in params) {[paramsstring appendformat:@ "%@=%@", Key,[params Objectforkey:key]];

if (Key! = [[params allKeys] lastobject]) {

[Paramsstring appendstring:@ "&"];
}
}4. Gets the final path of the request nsstring *fullstring = [urlstring stringbyappendingformat:@ "%@%@", str,paramsstring];5. Construction request NSURLRequest *r Equest = [[Nsurlrequest alloc] Initwithurl:[nsurl urlwithstring:fullstring] CachePolicy: Nsurlrequestreloadignoringlocalandremotecachedata timeoutinterval:60];//nsurlrequestcachepolicy Cache Policy6. Create Sessionnsurlsessionconfiguration *cofiguration = [Nsurlsessionconfiguration defaultsessionconfiguration]; Nsurlsession *session = [nsurlsession sessionwithconfiguration:cofiguration];7. Creating a Task(data task load)Nsurlsessiondatatask *task = [Session datataskwithrequest:request completionhandler:^ (NSData * _Nullable data, Nsurlresponse * _nullable response, Nserror * _nullable error) {

if (Error) {NSLog (@ "request failed"); }//Convert the acquired data from NSData to JSON ID type dataID jsonobject = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil]; }];8. Start execution of task [task resume];  Post request POST request is sent to the Web server as the actual content of the HTTP message, and the data is placed within the HTML header submission 1. Request address Urlnsurl *url = [nsurl urlwithstring:urlstring];2. Construct network request Nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url];** gets the argument string paramsstring (the dictionary is converted to a string, which can be omitted depending on the condition) nsmutablestring *paramsstring = [[nsmutablestring ALLOC] init];
For (NSString *key in params) {[paramsstring appendformat:@ "%@=%@", Key,[params Objectforkey:key]];

if (Key! = [[params allKeys] lastobject]) {

[Paramsstring appendstring:@ "&"];
}
} * * NSData *databody = [paramsstring datausingencoding:nsutf8stringencoding]; Request.    Httpbody = Databody; Request.    HttpMethod = @ "POST"; Request.timeoutinterval = 60;  3. Create Session Object
Nsurlsession *session = [Nsurlsession sharedsession];
4.Create task (data task load) Nsurlsessiondatatask *task = [Session datataskwithrequest:request completionhandler:^ (NSData * _Nul lable data, Nsurlresponse * _nullable response, Nserror * _nullable error) {if (error) {NSLog (@ "request Failed")                    ; }//parsing JSON data
ID jsonob = [nsjsonserialization jsonobjectwithdata:data options:nsjsonreadingallowfragments Error:nil]; }];

5.Start a task [task resume];   Third, download the task1. Request address Urlnsurl *url = [Nsurl urlwithstring:@ "Http://dl1.52pk.com:8088/soft/2013/Microsoft.Office.2010.CR_52pk.zip" ];2. Create request Nsurlrequest *request = [Nsurlrequest requestwithurl:url cachepolicy:nsurlrequestreturncachedataelseload Timeoutinterval:10];3. Creating sessionnsurlsessionconfiguration *cofiguration = [nsurlsessionconfiguration Defaultsessionconfiguration]; Nsurlsession *session = [nsurlsession sessionwithconfiguration:configuration delegate:self delegateQueue:[ Nsoperationqueue Mainqueue]]; 4. Create task (Download task to complete download file) With block callback does not execute proxy method Nsurlsessiondownloadtask *downloadtask = [session Downloadtaskwithrequest:request completionhandler:^ (Nsurl * _nullable location, Nsurlresponse * _Nullable response, Nserror * _nullable error) {//loaction: Storage path for downloaded files
//The file currently acquired is only a temporary file after the block call is destroyed
NSLog (@ "location:%@", location); }];  Create a task create a proxy method by using a download task without a block callback downloadtask = [session downloadtaskwithrequest:request];5. Task execution [Downloadtask R esume];6. Download pause and resume (breakpoint continuation) 6.1 Pause [Downloadtask cancelbyproducingresumedata:^ (NSData * _nullable resumedata) {
//Keep the downloaded data_resumedata = resumedata;//Global for easy continuation of the task when you find a breakpoint that continues to download//Destroy the current download task
Downloadtask = nil; }];  6.2 continue to download downloadtask = [_session downloadtaskwithresumedata:_resumedata];//Perform the download[Downloadtask resume];7. Methods of Nsurldownloaddelegate
7.1 Call this method when the download is complete
-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask
Didfinishdownloadingtourl: (Nsurl *) location
{
NSLog (@ "Download completed location:%@", location);
}

7.2 Real-time call at download to calculate download progress
-(void) Urlsession: (Nsurlsession *) session Downloadtask: (Nsurlsessiondownloadtask *) downloadtask
Didwritedata: (int64_t) Byteswritten
Totalbyteswritten: (int64_t) Totalbyteswritten
Totalbytesexpectedtowrite: (int64_t) Totalbytesexpectedtowrite
{
/*
byteswritten: Data size for this download
Totalbyteswritten: The current total downloaded data size
totalbytesexpectedtowrite: Total size of files to download
     */

NSLog (@ "Current download progress:%.2f%%", (float) totalbyteswritten/(float) totalbytesexpectedtowrite*100);
}   Iv. Uploading Tasks1. Request address Urlnsurl *url = [Nsurl urlwithstring:@ "Https://upload.api.weibo.com/2/statuses/upload.json"]; Upload images on Weibo interface 2. Create request requests Nsmutableurlrequest *request = [Nsmutableurlrequest requestwithurl:url cachepolicy: Nsurlrequestreturncachedataelseload timeoutinterval:10];3. Set Request Request 3.1 requests. HttpMethod = @ "POST", 3.2 Request header settings [request setvalue:@ "multipart/form-data; BOUNDARY=WJ" forhttpheaderfield:@ " Content-type "];3.3 API Required Parameters Nsdictionary *parameters = @{@" Access_token ": @" 2.00MJ342GXQPRWCEFC4CFDE8ECUW6YC "@" Status ": @" enter into "};3.4 file to be uploaded (convert picture to binary data) nsstring *path = [[NSBundle mainbundle] pathforresource:@" test "oftype:@" JPG " ]; NSData *imgdata = [NSData datawithcontentsoffile:path];3.5 stitching request Body nsstring*preboundary = [NSString stringWithFormat:@ "--       %@ ", @" WJ "]; Nsstring*endboundary = [NSString stringwithformat:@ "--%@--", @ "WJ"];

nsmutablestring *body = [[Nsmutablestring alloc] init];

Traverse Keys for (Nsstring*key in parameters) {
Get current key

If key is not a pic, it indicates that value is a character type, such as Name:boris
To add a dividing line, a newline must use \ r \ n
[Body appendformat:@ "%@\r\n", preboundary];
Add field name, change 2 lines
[Body appendformat:@ "content-disposition:form-data; name=\"%@\ "\r\n\r\n", key];
Add the value of the field [body appendformat:@ "%@\r\n", [parameters Objectforkey:key]];
}

Add dividing line, wrap
[Body appendformat:@ "%@\r\n", preboundary];
Declare pic field, file name boris.png [body appendformat:@ "content-disposition:form-data; name=\"%@\ "; filename=\"%@\ "\ r \ n" @ "    Pic ", @" Pic.png "]; Declares the format of the uploaded file [body appendformat:@ "Content-type:%@\r\n\r\n", @ "Image/png"];
Declaration Terminator:--wj--
NSString *end=[[nsstring alloc]initwithformat:@ "\r\n%@", endboundary];
Declare Myrequestdata, which is used to put the HTTP body


Nsmutabledata *myrequestdata=[nsmutabledata data];
Converts the body string to a binary in the UTF8 format
[Myrequestdata appenddata:[body datausingencoding:nsutf8stringencoding];
Add the data of image to [Myrequestdata Appenddata:imgdata]; Join Terminator--wj--[Myrequestdata appenddata:[end datausingencoding:nsutf8stringencoding];  3.6 Set the request body requests. Httpbody = formdata;4. Create an upload task (Upload task to complete uploading a file) nsurlsessionuploadtask *upload = [_session uploadtaskwithrequest:request FROMDATA:FORMD ATA completionhandler:^ (NSData * _nullable data, Nsurlresponse * _nullable response, Nserror * _nullable error) {

if (!error) {
NSLog (@ "upload complete");

}
}];

5.Perform tasks [upload resume];        

Get request sent by session, POST request, upload, download

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.