IOS development ASIHttpRequest sends and downloads data

Source: Internet
Author: User

IOS development ASIHttpRequest sends and downloads data

Send data

This article describes how to develop ASIHttpRequest for iOS to send data, including setting request headers, using ASIFormDataRequest POST forms, PUT requests, and custom POST requests.

 Set request Header

ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url];

[Request addRequestHeader: @ "Referer" value: @ "http://www.dreamingwish.com/"];

Use ASIFormDataRequest POST form

Generally, data is sent in 'application/x-www-form-urlencoded' format. If binary data or files are uploaded, the format is automatically changed to 'multipart/form-data '.

The data in the file is loaded from the disk only when necessary. Therefore, as long as the web server can process the data, it is no problem to upload large files.

ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url];

[Request setPostValue: @ "Ben" forKey: @ "first_name"];

[Request setPostValue: @ "Copsey" forKey: @ "last_name"];

[Request setFile: @ "/Users/ben/Desktop/ben.jpg" forKey: @ "photo"];

The mime header of the data is automatically determined, but if you want to customize the mime header, then the following is true:

ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url];

// Upload a file on disk

[Request setFile: @ "/Users/ben/Desktop/ben.jpg" withFileName: @ "myphoto.jpg" andContentType: @ "image/jpeg"

ForKey: @ "photo"];

// Upload an NSData instance

[Request setData: imageData withFileName: @ "myphoto.jpg" andContentType: @ "image/jpeg" forKey: @ "photo"];

You can use the addPostValue method to send multiple data with the same name (mengwei: the server will display the data in an array ):

ASIFormDataRequest * request = [ASIFormDataRequest requestWithURL: url];

[Request addPostValue: @ "Ben" forKey: @ "names"];

[Request addPostValue: @ "George" forKey: @ "names"];

[Request addFile: @ "/Users/ben/Desktop/ben.jpg" forKey: @ "photos"];

[Request addData: imageData withFileName: @ "george.jpg" andContentType: @ "image/jpeg" forKey: @ "photos"];

  PUT request, custom POST request

If you want to send a PUT request, or you want to customize a POST request, use appendPostData: Or appendPostDataFromFile:

ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url];

[Request appendPostData: [@ "This is my data" dataUsingEncoding: NSUTF8StringEncoding];

// Default becomes POST when you use appendPostData:/appendPostDataFromFile:/setPostBody:

[Request setRequestMethod: @ "PUT"];

 Download data

This article describes how to download data from iOS development ASIHTTPRequest, including setting to directly download server response data to a file, processing server response data received, PUT requests, and obtaining HTTP status codes, read the response header, process text encoding, and redirect.

Directly download server response data to a file

If the requested resources are large, you can directly download the data to the file to save memory. In this case, ASIHTTPRequest does not keep all returned data in the memory at one time.

When downloadDestinationPath is downloaded, the data is first stored in a temporary file. At this time, the file path name is stored in temporaryFileDownloadPath (mengwei: if this value is not set, a file name is automatically generated. in the simulator, the file is created in $ TMPDIR ).

ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url];

[Request setDownloadDestinationPath: @ "/Users/ben/Desktop/my_file.txt"];

When the request is complete, one of the following two things will happen:

If the data is compressed (gzip), the compressed file will be decompressed to downloadDestinationPath, and the temporary file will be deleted.

If the data is not compressed, the file will be moved to downloadDestinationPath. The conflict resolution method is to overwrite the existing file.

Note: If the server response data is empty, the file will not be created. If your returned data may be empty, you should first check whether the downloaded file exists and then perform operations on the file.

  Process received Server Response Data

If you want to process the server response data (for example, you want to use the stream parser to process the downloaded data stream), you should implement the proxy function request: didReceiveData :. Note that if you do this, ASIHTTPRequest will not fill the responseData to the memory, nOr Write the data into the file (downloadDestinationPath)-You must do either of these two things by yourself ).

 Get http status code

ASIHTTPRequest does not process HTTP status codes (except for redirection and authorization status codes, which will be described below). Therefore, you must check the status values and handle them correctly.

ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url];

[Request startSynchronous];

Int statusCode = [request responseStatusCode];

NSString * statusMessage = [request responseStatusMessage];

  Read Response Header

ASIHTTPRequest * request = [ASIHTTPRequest requestWithURL: url];

[Request startSynchronous];

NSString * poweredBy = [[request responseHeaders] objectForKey: @ "X-Powered-By"];

NSString * contentType = [[request responseHeaders] objectForKey: @ "Content-Type"];

Process Text Encoding

ASIHTTPRequest tries to read the encoding information (Content-Type header information) of the returned data ). If it finds the encoding information, it sets the encoding information to the appropriate NSStringEncoding. If it does not find the encoding information, it sets the encoding to the default encoding (NSISOLatin1StringEncoding ).

When you call [request responseString], ASIHTTPRequest will try to convert the returned Data to NSString using responseEncoding.

  Process redirection

When the following HTTP status code occurs, ASIHTTPRequest automatically redirects to the new URL:

301 Moved Permanently

302 Found

303 See Other

When a redirection occurs, the response data values (responseHeaders, responseCookies, responseData, responseString, and so on) are mapped to the returned data of the final address.

When a URL is cyclically redirected, the cookie set on this URL will be stored in the global domain and sent to the server as appropriate.

Cookies set on any of the urls encountered during a redirection cycle will be stored in the global cookie store, and will be represented to the server on the redirected request when appropriate.

You can disable automatic redirection: Set shouldRedirect to NO.

By default, the GET request is used for automatic redirection (the Request body is empty ). This behavior complies with the behavior of most browsers, but HTTP spec requires that 301 and 302 redirection use the original method.

To use the original method (including the request body) for 301 and 302 redirection, set shouldUseRFC2616RedirectBehaviour to YES before initiating the request.

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.