Web Development Summary
One basic elements of HTTP requests
- 1. Request URL: Which path the client uses to locate the server
2. Request parameters: Data sent by the client to the server
- * such as user name and password to be sent at login
3. Return results: Data returned by the server to the client
- * Typically JSON data or XML data
II. Basic HTTP request Steps (Mobile client)
1. Stitching "Request URL" + "?" + "Request parameter"
- * Format of request parameter: Parameter name = argument value
- * Multiple request parameters separated by &: Parameter name 1 = parameter value 1& argument Name 2 = parameter value 2
- * For example: http://localhost:8080/MJServer/login?username=123&pwd=456
2. Sending the request
3. Parsing the data returned by the server
Third, JSON parsing
1. Using Nsjsonserialization class parsing
- * JSON data (NSData)--Foundation-oc objects (Nsdictionary, Nsarray, NSString, NSNumber)
- + (ID) jsonobjectwithdata: (NSData *) Data options: (nsjsonreadingoptions) opt error: (NSERROR *) error;
2.JSON Analytic law
- * {}--nsdictionary @{}
- * []--Nsarray @[]
- * "--nsstring @" "
- *---NSNumber @10
Iv. nsurlconnection
1. Publish an asynchronous request 01--block callback
- + (void) Sendasynchronousrequest: (nsurlrequest*) Request
- Queue: (nsoperationqueue*) queue
- Completionhandler: (void (^) (nsurlresponse* response, nsdata* data, nserror* connectionerror)) handler
- * Request: Requests that need to be sent
- * Queue: Generally with the home row, storage handler this task
- * Handler: When the request is complete, the block is automatically called
2. Basic steps for sending requests using nsurlconnection
1> Creating URLs
- Nsurl *url = [Nsurl urlwithstring:@ "http://4234324/5345345"];
2> Creating a Request
- Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
3> Sending requests
- [Nsurlconnection sendasynchronousrequest:request queue:queue Completionhandler:
- ^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
4> processing the data returned by the server
Five, XML
1. Syntax
1> Document Declaration
- <?xml version= "1.0" encoding= "UTF-8"?>
2> elements
3> Property
- <videos>
- <video name= "Small yellow No. 01" length= "/>"
- <video name= "Small yellow No. 01" length= "/>"
- </videos>
- * Videos and video are elements (nodes)
- * Name and length are called attributes of the element
- * The video element is a child element of the videos element
2. Parsing
1> Sax parsing: Parse-by-element down, for large files
2> Dom parsing: A breath of loading the entire XML document into memory, suitable for small files, using the simplest
VI. Communication Process for HTTP
1. Request
1> Request Line: Request method, request path, version of HTTP protocol
- Get/mjserver/resources/images/1.jpg http/1.1
2> Request Header: Some descriptive information for the client
- * User-agent: Client-side environment (software environment)
3> Request Body: Post request only this thing
- * Request parameters, data sent to the server
2. Response
1> status line (response line): Version of HTTP protocol, response status Code, response status description
2> response Header: Some descriptive information about the server
- * Content-type: The content type returned to the client by the server
- * Content-length: The length of the content returned to the client by the server (such as the size of the file)
3> Entity content (response body)
- * The server returns specific data to the client, such as file data
Vii. Request method for HTTP
1.GET
1> Features
- * All request parameters are stitched behind the URL
2> Disadvantages
- * All request data is exposed in the URL, not too secure
- * URL is limited in length and cannot send too many parameters
3> Use occasions
- * If you only request data from the server, you typically use GET requests
4> How to send a GET request
* Default is GET request
1.URL
- Nsurl *url = [Nsurl urlwithstring:@ "http://www.baidu.com"];
2. Request
- Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
3. Sending the request
- [Nsurlconnection sendasynchronousrequest:request queue:[nsoperationqueue Mainqueue] completionHandler:^ ( Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
- }];
2.POST
1> Features
- * Place all request parameters in the request body (httpbody)
- * Theoretically, there is no limit to the size of the data sent to the server
2> Use occasions
- * In addition to requesting data from the server, you can use the POST request
- * If the data sent to the server is some privacy, sensitive data, you must use the POST request
3> How to send a POST request
1. Create a URL: request path
- Nsurl *url = [Nsurl urlwithstring:@ "Http://localhost:8080/MJServer/login"];
2. Create a request
- Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
- Set Request method
- Request. HttpMethod = @ "POST";
- Set Request body: Request parameters
- NSString *param = [NSString stringwithformat:@ "username=%@&pwd=%@", Usernametext, Pwdtext];
- NSString-NSData
- Request. Httpbody = [param datausingencoding:nsutf8stringencoding];
Eight, the common method of Nsmutableurlrequest
1. Set timeout
Request.timeoutinterval = 5;
Nsurlrequest is not able to set the timeout because the object is immutable
Nine, url transcoding
1.URL can not contain Chinese, you have to transcode the Chinese (plus a bunch of%)
- NSString *urlstr = [NSString stringwithformat:@ "http://localhost/login?username= drink &pwd=123"];
- URLSTR = [Urlstr stringbyaddingpercentescapesusingencoding:nsutf8stringencoding];
- Urlstr = = @ "http://localhost/login?username=%E5%96%9D%E5%96%9D&pwd=123"
X. Data security
1. Network Data encryption
1> Encrypted objects: Privacy data, such as passwords, bank information
2> Encryption Scheme
* Submit privacy data, must use POST request
* Encrypt private data using cryptographic algorithms, such as MD5
3> encryption Enhancement: In order to increase the difficulty of the crack
- * 2 Md5:md5 for clear text (MD5 ($pass))
- * Salt the plaintext before md5:md5 ($pass. $salt)
2. Local Storage encryption
1> Encrypted objects: Important data, such as game data
3. Code Security issues
1> now has tools and techniques to decompile source code: Reverse Engineering
- * The anti-compilation is pure C language, the readability is not high
- * At the very least, you can know which frames are used in the source code.
2> reference book: "Reverse engineering of iOS"
3> Solution: Confusing code before publishing
* Before confusing
- @interface Icocosperson:nsobject
- -(void) run;
- -(void) eat;
- @end
* After confusion
- @interface A:nsobject
- -(void) A;
- -(void) B;
- @end
Xi. monitoring the status of the network
1. Active monitoring and monitoring of network status
Whether WiFi
- + (BOOL) Isenablewifi {
- return ([[reachability Reachabilityforlocalwifi] currentreachabilitystatus]! = notreachable);
- }
Is 3G
- + (BOOL) isenable3g {
- return ([[reachability reachabilityforinternetconnection] currentreachabilitystatus]! = notreachable);
- }
2. Monitor network status
1> Monitoring Notifications
- [[Nsnotificationcenter Defaultcenter] addobserver:self selector: @selector (networkstatechange) Name: Kreachabilitychangednotification Object:nil];
2> Start listening to network status
- Get Reachability Object
- self.reachability = [reachability reachabilityforinternetconnection];
- Start monitoring the network
- [Self.reachability Startnotifier];
3> Remove Listener
- [Self.reachability Stopnotifier];
- [[Nsnotificationcenter Defaultcenter] removeobserver:self];
————————————————————————————————————————————————————————————————————————————————————————
First, large file download
1. Scenario: Leveraging Nsurlconnection and its proxy approach
1> send a request
1.URL
- Nsurl *url = [Nsurl urlwithstring:@ "Http://localhost:8080/MJServer/resources/videos.zip"];
2. Request
- Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
3. Download (after the Conn object is created, an asynchronous request is automatically initiated)
- [Nsurlconnection connectionwithrequest:request delegate:self];
2> processing the data returned by the server in the proxy method
/**
When you receive a response from the server:
1. Create an empty file
2. Use a handle object to associate the empty file with the purpose of using the handle object to write the data behind the file conveniently
*/
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response
{
File path
NSString *caches = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject];
NSString *filepath = [Caches stringbyappendingpathcomponent:@ "Videos.zip"];
Create an empty file into the sandbox
Nsfilemanager *mgr = [Nsfilemanager Defaultmanager];
[Mgr Createfileatpath:filepath Contents:nil Attributes:nil];
Create a file handle to write data to
Self.writehandle = [Nsfilehandle Filehandleforwritingatpath:filepath];
}
/**
Use the handle object to append data to the last face of the file when the file data returned by the server is received
*/
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data
{
Move to the last side of a file
[Self.writehandle Seektoendoffile];
Writing data to a sandbox
[Self.writehandle Writedata:data];
}
/**
Close the handle object when all data is received
*/
-(void) connectiondidfinishloading: (nsurlconnection *) connection
{
Close File
[Self.writehandle CloseFile];
Self.writehandle = nil;
}
2. Note: Never use Nsmutabledata to splice data returned by the server
Ii. Nsurlconnection method for sending asynchronous requests
1.block form-Except for large file download, it can be used in this form
- [Nsurlconnection sendasynchronousrequest:<# (Nsurlrequest *) #> queue:<# (Nsoperationqueue *) #> completionhandler:^ (Nsurlresponse *response, NSData *data, Nserror *connectionerror) {
2. Proxy form-generally used in large file download
1.URL
- Nsurl *url = [Nsurl urlwithstring:@ "http://localhost:8080/MJServer/login?username=123&pwd=123"];
2. Request
- Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
3. Download (after the Conn object is created, an asynchronous request is automatically initiated)
- [Nsurlconnection connectionwithrequest:request delegate:self];
Third, nsurlsession
1. Steps to use
- 1> Get Nsurlsession Object
- 2> using Nsurlsession objects to create a corresponding task (Task)
- 3> Start Task ([Task resume])
2. Get Nsurlsession Object
1> [Nsurlsession Sharedsession]
2>
- Nsurlsessionconfiguration *cfg = [Nsurlsessionconfiguration defaultsessionconfiguration];
- Self.session = [nsurlsession sessionwithconfiguration:cfg delegate:self delegatequeue:[nsoperationqueue MainQueue]];
3. Task type
1> Nsurlsessiondatatask
* Purpose: Get\post request for non-file download
- Nsurlsessiondatatask *task = [Self.session datataskwithrequest:request];
- Nsurlsessiondatatask *task = [Self.session Datataskwithurl:url];
- Nsurlsessiondatatask *task = [self.session datataskwithurl:url completionhandler:^ (NSData *data, NSURLResponse * Response, Nserror *error) {
- }];
2> Nsurlsessiondownloadtask
* Use: For file download (small file, large file)
- Nsurlsessiondownloadtask *task = [Self.session downloadtaskwithrequest:request];
- Nsurlsessiondownloadtask *task = [Self.session Downloadtaskwithurl:url];
- Nsurlsessiondownloadtask *task = [self.session downloadtaskwithurl:url completionhandler:^ (NSURL *location, Nsurlresponse *response, Nserror *error) {
- }];
———————————————————————————————————————————————————————————————— the difference between AFN and ASI (for interview)first, the bottom realization
1> AFN based on OC Nsurlconnection and Nsurlsession
2> ASI's underlying cfnetwork framework based on pure C language
3> ASI has a higher operating performance than AFN
ii. Data processing for the return of the server
1> ASI does not provide direct data processing to the server, directly returning data\string
2> AFN provides a variety of ways to process server data
- * JSON processing
- * XML processing
- * Other processing
third, the process of monitoring the request
1> AFN provides success and failure two blocks to listen for requests (only for success and failure)
- * Success: Call after successful request
- * Failure: Call after request failed
The 2> ASI offers 3 solutions, each of which listens to the complete process of the request.
(Listener requests Start, receive response header information, receive specific data, accept, request failed)
- * Become an agent, abide by the agreement, implement the agent method in the Agreement
- * Become an agent, do not comply with the protocol, custom proxy methods
- * Set block
Iv. Ease of use in file downloads and file uploads
1> AFN
- * Not easy to listen to download progress and upload progress
- * Not easy to implement a breakpoint continuation
- * Generally only used to download a small file
2> ASI
- * Very easy to download and upload
- * Very easy to listen to download progress and upload progress
- * Very easy to implement the breakpoint continued to pass
- * Download or large or small files are OK
Five, ASI provides more practical functions
1> Control Circle do not relay in the request process
2> can easily set dependencies between requests: Each request is a Nsoperation object
3> can manage all requests uniformly (also specifically providing a call to Asinetworkqueue to manage all request objects)
- * Pause \ Resume \ Cancel all requests
- * Monitor the download progress and upload progress of all requests in the entire queue
iOS Development--Network Programming OC Chapter & Summary