IOS UI14_GET-POST

Source: Internet
Author: User

IOS UI14_GET-POST

//

// ViewController. m

// UI14_GET-POST

//

// Created by dllo on 15/8/17.

// Copyright (c) 2015 zhozhicheng. All rights reserved.

//

 

# Import ViewController. h

 

@ Interface ViewController ()

-(IBAction) synGET :( id) sender;

-(IBAction) synPOST :( id) sender;

-(IBAction) asynGET :( id) sender;

-(IBAction) asynPOST :( id) sender;

-(IBAction) block :( id) sender;

@ Property (nonatomic, retain) UIImageView * imageView;

@ Property (nonatomic, retain) NSMutableData * data;

@ End

 

@ Implementation ViewController

 

-(Void) viewDidLoad {

[Super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

Self. imageView = [[UIImageView alloc] initWithFrame: CGRectMake (200,100,150,150)];

Self. imageView. backgroundColor = [UIColor cyanColor];

[Self. view addSubview: self. imageView];

[_ ImageView release];

}

 

-(Void) didReceiveMemoryWarning {

[Super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

 

-(IBAction) synGET :( id) sender {

// NSLog (@ GET synchronization request );

NSString * strURL = @ http://api.map.baidu.com/place/v2/search? Query = Bank®Ion = Dalian & output = json & ak = 6e823f587c95f0148c%3539b99295;

// A normal URL cannot contain Chinese characters. It can only contain uppercase and lowercase letters, numbers, and special characters. for example, if you encounter a URL with Chinese characters, encode it first.

NSString * strEncode = [strURL stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

// NSLog (% @, strEncode );

// Next, initiate a network request after the URL meets the requirements. The network request is divided into three steps.

// 1. Create an NSURL Based on the encoded URL

NSURL * url = [NSURL URLWithString: strEncode];

// 2. Send a request

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url];

// 3. Return the data we want, an NSData object

// Three parameters: the first parameter is the newly created request, the second parameter is the returned response, and the third parameter is the error message.

NSURLResponse * response = nil;

NSError * error = nil;

NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: & response error: & error];

// Parse the returned data in json format.

// Print all the bank names

NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: nil];

NSMutableArray * arr = dic [@ results];

For (NSDictionary * dic in arr ){

NSLog (@ % @, dic [@ name]);

}

 

 

}

 

-(IBAction) synPOST :( id) sender {

NSLog (@ POST );

NSString * strURL = @ http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx;

NSURL * url = [NSURL URLWithString: strURL];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url];

// Next is the unique part of the POST request

// Set the request method to post first. The default value is GET.

[Request setHTTPMethod: @ POST];

// Put the request content in the request body.

NSString * bodyStr = @ date = 20131129 & startRecord = 1 & len = 30 & udid = 1234567890 & terminalType = Iphone & cid = 213;

// Convert the request string to an NSData object.

NSData * bodyData = [bodyStr dataUsingEncoding: NSUTF8StringEncoding];

// Put bodyData in the request

[Request setHTTPBody: bodyData];

 

NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];

// Json Parsing

NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: nil];

NSLog (@ % @, dic );

 

}

 

-(IBAction) asynGET :( id) sender {

NSLog (@ GET asynchronous request );

NSString * strURL = @ brief;

NSURL * url = [NSURL URLWithString: strURL];

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url];

// The first two steps are the same as before. The third step changes and performs asynchronous operations through proxy.

[NSURLConnection connectionWithRequest: request delegate: self];

 

 

}

-(Void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response

{

// This method is used as long as the response information returned by the server is received. In this method, we need to initialize the container data that receives the data.

Self. data = [NSMutableData data];

 

 

}

-(Void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data

{

// This method is used as long as the data is returned.

// Append indicates accumulation.

[Self. data appendData: data];

}

-(Void) connectionDidFinishLoading :( NSURLConnection *) connection

{

// At this point, the entire request has ended. You need to assign a value to the image in the imageView to the returned DATA.

Self. imageView. image = [UIImage imageWithData: self. data];

 

}

# Warning synchronous and asynchronous GET requests are exactly the same in the step, but the sendSyn method is used in the third step, the proxy method is used for synchronization, And the asynchronous method is based on synchronization.

 

 

-(IBAction) asynPOST :( id) sender {

NSLog (@ POST asynchronous );

NSString * strURL = @ http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx;

// 1. Create an NSUrl

NSURL * url = [NSURL URLWithString: strURL];

// 2. Request

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url];

// 3. request Method

[Request setHTTPMethod: @ POST];

NSString * bodyStr = @ date = 20131129 & startRecord = 1 & len = 30 & udid = 1234567890 & terminalType = Iphone & cid = 213;

NSData * bodyData = [bodyStr dataUsingEncoding: NSUTF8StringEncoding];

// Add to request

[Request setHTTPBody: bodyData];

//

// The Network request is requested in the Child thread. The requested data must be implemented through the control as the carrier, and the data must be displayed in the main thread, the second parameter is to specify the thread to which the data is returned.

[NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError ){

// The parameter data is the data we requested, and the data parsing will be performed in the block.

// Json Parsing

NSMutableDictionary * dic = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: nil];

NSLog (@ % @, dic );

 

}];

 

}

 

-(IBAction) block :( id) sender {

NSLog (@ GET asynchronously blocks );

NSString * str = @ brief;

// 1. Create an NSURL

NSURL * url = [NSURL URLWithString: str];

// 2. Send a request

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url];

// 3. asynchronous

[NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError ){

// Data processing is still in the block

Self. imageView. image = [UIImage imageWithData: data];

}];

 

}

@ End

# Warning summarizes the network request steps: 1. create an NSURL object based on the URL string. create a request based on the url object. send the request and obtain the request object. The difference between synchronous and asynchronous is that the selection of request methods is different.

# Warning POST is one more than GET, and a body needs to be added to 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.