Swift language IOS8 development war 25 network communication Get and Post methods, swiftios8

Source: Internet
Author: User
Tags html header

Swift language IOS8 development war 25 network communication Get and Post methods, swiftios8

Get gets data from the server, and Post transfers data to the server. For the Get method, the server uses Requset. QueryString to obtain the value of the variable. For the Post method, the server uses Request. Form to obtain the submitted data. Get is to add the parameter data queue to the URL referred to by the ACTION attribute of the submission form. The values correspond to each field in the form one by one and can be seen in the URL. Post uses the HTTP Post mechanism to place fields in the form and their content in the html header and send them to the URL address referred to by the ACTION attribute. You cannot see this process.

Get is very low in security, and Post is highly secure, but the Get method is more efficient than Post.

Therefore, we recommend that you use Get for query and Post for addition, deletion, and modification.

In the Development war note 24th, the synchronous method used to obtain weather information is a Get synchronous request. Please refer to the following code:

Import UIKitclass ViewController: UIViewController {@ IBAction func showWeatherJson (sender: UIButton) {// create url var url: NSURL! = NSURL (string: "http://www.weather.com.cn/adat/sk/101010100.html") // create the request object var urlRequest: NSURLRequest = NSURLRequest (URL: url, cachePolicy: NSURLRequestCachePolicy. useProtocolCachePolicy, timeoutInterval: 10) // create the response object var response: NSURLResponse? // Create the error object var error: NSError? // Send the request var data: NSData? = NSURLConnection. sendSynchronousRequest (urlRequest, returningResponse: & response, error: & error) if error! = Nil {println (error ?. Code) println (error ?. Description)} else {var jsonString = NSString (data: data !, Encoding: NSUTF8StringEncoding) println (jsonString )}}}

Here, when creating the NSURLRequest object, a more complex constructor is used:

URL parameter: Request Path

CachePolicy parameter: Cache Protocol

TimeoutInterval parameter: Network request timeout (unit: seconds)

The cache Protocol is an enumeration type:

Enum NSURLRequestCachePolicy: UInt {case UseProtocolCachePolicy // Basic Policy case ReloadIgnoringLocalCacheData // ignore local cache case ReloadIgnoringLocalAndRemoteCacheData // Unimplemented ignores any Cache Policy, always re-download case ReturnCacheDataElseLoad from the source address // first use the cache, no local cache, then use the source address to download case ReturnCacheDataDontLoad // use the local cache, Never download, if there is no local cache, the request fails, this policy is mostly used for offline Operations case ReloadRevalidatingCacheData // Unimplemented. If the local cache is valid, it is not downloaded. In other cases, it is downloaded again from the source address}

The following describes the asynchronous Get request method:
Func asynchronousGet () {// create an NSURL object var url: NSURL! = NSURL (string: "<span style =" font-family: Arial, Helvetica, sans-serif; "> http://api.hudong.com/iphonexml.do? Type = focus-c </span> <span style = "font-family: Arial, Helvetica, sans-serif;"> ") // directly write the parameters to the path </span> // create the request object var urlRequest: NSURLRequest = NSURLRequest (URL: url, cachePolicy: NSURLRequestCachePolicy. useProtocolCachePolicy, timeoutInterval: 10) // network connection object var conn: NSURLConnection? = NSURLConnection (request: urlRequest, delegate: self )}
After connecting to the server, use the following two asynchronous request proxy Methods NSURLConnectionDataDelegate to receive relevant data.

Func connection (connection: NSURLConnection, response: NSURLResponse) {// receive response} var jsonData: NSMutableData = NSMutableData () func connection (connection: NSURLConnection, didReceiveData: NSData) {// receives the data. This method executes jsonData several times based on the data size. appendData (data )}

The Post synchronization method is as follows: Put the parameters in the HTTP body, which is highly secure.

Import UIKitclass ViewController: UIViewController {@ IBAction func showWeatherJson (sender: UIButton) {// create url var url: NSURL! = NSURL (string: "http://api.hudong.com/iphonexml.do") // create the request object var urlRequest: NSMutableURLRequest = NSMutableURLRequest (URL: url, cachePolicy: NSURLRequestCachePolicy. useProtocolCachePolicy, timeoutInterval: 10) urlRequest. HTTPMethod = "POST" // set the request method to post. The default value is GET var str: String = "type = focus-c" // set the parameter var data: NSData = str. dataUsingEncoding (NSUTF8StringEncoding, allowLossyConversion: true )! UrlRequest. HTTPBody = data // create a response object var response: NSURLResponse? // Create the error object var error: NSError? // Send the request var received: NSData? = NSURLConnection. sendSynchronousRequest (urlRequest, returningResponse: & response, error: & error) if error! = Nil {println (error ?. Code) println (error ?. Description)} else {var jsonString = NSString (data: received !, Encoding: NSUTF8StringEncoding) println (jsonString )}}}

The asynchronous Post request method is as follows:

Var url: NSURL! = NSURL (string: "http://api.hudong.com/iphonexml.do") // create the request object var urlRequest: NSMutableURLRequest = NSMutableURLRequest (URL: url, cachePolicy: NSURLRequestCachePolicy. useProtocolCachePolicy, timeoutInterval: 10) urlRequest. HTTPMethod = "POST" // set the request method to post. The default value is GET var str: String = "type = focus-c" // set the parameter var data: NSData = str. dataUsingEncoding (NSUTF8StringEncoding, allowLossyConversion: true )! UrlRequest. HTTPBody = data var connection = NSURLConnection (request: urlRequest, delegate: self)

Then you can perform operations in the proxy method.




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.