Use of network protocols
# Import ViewController. h
@ Interface ViewController ()
@ End
@ Implementation ViewController
/**
*
Http is a Hyper Text Tansfer Protocol. All www files must comply with this Protocol standard.
Http is a protocol for browsing and transmitting data on the World Wide Web. It accesses remote network resources in the format of http: // server address resource address http // www.baidu.com/user/info
IP protocol corresponds to the network layer; TCP corresponds to the transport layer; HTTP corresponds to the Application Layer
The role of http:
01. Specify the data transmission format between the client and server
02. Enable the client and server to communicate data effectively
Benefits of using HTTP:
01. simple and fast. Because the HTTP protocol is simple, the http server's program size is small, so the communication speed is fast.
02. Flexible, HTTP allows transmission of any type of data
03. HTTP is a non-persistent connection. Only one request is allowed for each connection. The server immediately disconnects the connection after making a response to the customer service request. This method saves transmission time.
HTTP Communication Process:
01. request data from the client to the server
02. The response server returns the corresponding data from the customer service.
***********************
HTTP Request Method: get post
Get will put the request content on the request connection (spliced to the link address) (get is used by default for data requests)
For example: www.baidu.com/user/login? Username = streamline, psw = 123
Get features:
01. The browser and server have a length limit on the URL. Therefore, the parameters attached to the URL are limited. Generally, the length cannot exceed 1 kb.
02. The request data will be exposed in the interface
All the post parameters are placed in the Request body to ensure data security. There is no specific length limit (the only limit is the server's capacity)
GET and POST usage:
01. If you need to transmit a large amount of data, such as file upload, you can only use POST requests.
02. GET is more secure than POST. If it contains confidential and sensitive information, POST requests are recommended.
03. If you want to add, delete, and modify data, POST is recommended.
04. If you only request data (data query), we recommend that you use GET
URL: Uniform Resource Locator (Uniform Resource Locator) the unique Resource address on the Internet can be found through one URL.
Psw: Password md5 (password) Encryption
**********************
Network request: Synchronous asynchronous request
01. synchronous requests and other operations are fully executed before they can continue to be executed. Feature: if the requested operation is not completed, the system will not respond to any events (in the same thread)
02. When an asynchronous request is running, it will use idle time to execute the operations in it and will not affect other operations in the same thread.
*/
-(Void) viewDidLoad {
[Super viewDidLoad];
// [Self loadData1];
// [Self loadData2];
// [Self loadData3];
// [Self loadData4];
// [Self loadData5];
[Self loadData6];
}
// Obtain the content (string) in the URl through the URL)
-(Void) loadData1
{
// Convert the string to NSURL
NSURL * url = [NSURL URLWithString: @ http: // 192.168.1.126: 8080/cms4/login/doLogin. action];
NSString * content = [NSString stringWithContentsOfURL: url encoding: NSUTF8StringEncoding error: nil];
NSLog (@ % @, content );
}
// Obtain the data in the URl through the URL
-(Void) loadData2
{
NSURL * url = [NSURL URLWithString: @ http://preview.quanjing.com/is_rm001/is0997q92.jpg.pdf;
NSData * data = [NSData dataWithContentsOfURL: url];
UIImageView * imageView = [[UIImageView alloc] initWithFrame: self. view. frame];
ImageView. contentMode = UIViewContentModeScaleAspectFill;
ImageView. image = [UIImage imageWithData: data];
[Self. view addSubview: imageView];
}
// Synchronous request
-(Void) loadData3
{
NSURL * url = [NSURL URLWithString: @ http://preview.quanjing.com/is_rm001/is0997q92.jpg.pdf;
// Instantiate a request object containing the request address
NSURLRequest * request = [NSURLRequest requestWithURL: url];
// Data is the data returned by the server. NSURLConnection is the request class.
NSData * data = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
UIImageView * imageView = [[UIImageView alloc] initWithFrame: self. view. frame];
ImageView. contentMode = UIViewContentModeScaleAspectFill;
ImageView. image = [UIImage imageWithData: data];
[Self. view addSubview: imageView];
}
// Asynchronous request
-(Void) loadData4
{
UIImageView * imageView = [[UIImageView alloc] initWithFrame: self. view. frame];
ImageView. contentMode = UIViewContentModeScaleAspectFill;
[Self. view addSubview: imageView];
NSURL * url = [NSURL URLWithString: @ http://preview.quanjing.com/is_rm001/is0997q92.jpg.pdf;
NSURLRequest * request = [NSURLRequest requestWithURL: url];
// Requests need to be sent asynchronously through links
// Thread
NSOperationQueue * queue = [[NSOperationQueue alloc] init];
// Send an asynchronous request to be executed in this thread
[NSURLConnection sendAsynchronousRequest: request queue: queue completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError ){
// Response content (response status code and error) data returned by the response server to the data required by the client
NSLog (@ % @, response );
ImageView. image = [UIImage imageWithData: data];
}];
}
// Get put the transmitted data in the link address
-(Void) loadData5
{
NSString * interfaceString = @ http://apis.baidu.com/showapi_open_bus/mobile/find;
NSString * requestContentString = @ num = 18786084133;
NSString * uselString = [NSString stringWithFormat: @ % @? % @, InterfaceString, requestContentString];
// Convert the character of the link address to NSUTF8StringEncoding
NSURL * url = [NSURL URLWithString: [uselString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
// For a variable request, you can add the Request Method and request headers or more
// (NSTimeInterval) if the time required for a request exceeds the time limit, the request is not cached in the cachePolicy method.
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
// Specify the http Request Method
Request. HTTPMethod = @ GET;
NSString * apiKey = @ e7f5ac9e7c42a6c8cb125ee1d7e8779e;
// Send the apiKey to the Request Header specified by the server. The KEY required by forHTTPHeaderField is the key specified by the server.
[Request addValue: apiKey forHTTPHeaderField: @ apikey];
[NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError ){
NSLog (@ % @, response );
// Parse the json File
// Convert data into a json File
NSDictionary * info = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: nil];
NSLog (%%, info [@ showapi_res_body] [@ city], info [@ showapi_res_body] [@ name], info [@ showapi_res_body] [@ num]);
}];
}
// Post request
-(Void) loadData6
{
NSURL * url = [NSURL URLWithString: @ http://www.weihuok.com/customer2/getservice#;
// The device model of the Request Parameter PlatformType
NSDictionary * dic =@{@ PlatformType: @ 3 };
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10];
// Set the HTTP Request Method
Request. HTTPMethod = @ POST;
// Set Request Parameters
// DataUsingEncoding converts a string to data
// HTTPBody requires data
Request. HTTPBody = [[NSString stringWithFormat:, dic] dataUsingEncoding: NSUTF8StringEncoding];
// Send the request
[NSURLConnection sendAsynchronousRequest: request queue: [[NSOperationQueue alloc] init] completionHandler: ^ (NSURLResponse * response, NSData * data, NSError * connectionError ){
NSDictionary * info = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingAllowFragments error: nil];
NSLog (@ % @, info );
}];
}
-(Void) didReceiveMemoryWarning {
[Super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@ End