GET and POST requests in iOS development practices
GET and POST requests are the most common HTTP requests. Familiarize yourself with the HTTP communication process before talking about the request method:
Request
1. Request Line: Request Method, request path, and HTTP Version
GET/MJServer/resources/images/1.jpg HTTP/1.1
2. Request Header: some descriptions of the Client
Host: 192.168.1.111: 8080 // address of the server host to be accessed by the client
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9) Firefox/30.0 // client type, client software environment
Accept: Text/html, // data types that the client can receive
Accept-Language: Zh-cn // language environment of the Client
Accept-Encoding: Gzip // The data compression format supported by the client
3. Request body: This is available in POST requests.
Request Parameter, data sent to the server
Response
1. Status line (Response line): HTTP Protocol version, response status code, response status description
Server: Apache-Coyote/1.1 // server type
Content-Type: Image/jpeg // type of returned data
Content-Length: 56811 // The length of the returned data
Date: Mon, 23 Jun 2014 12:54:52 GMT // Response Time
2. Response Header: Some server descriptions
Content-Type: the Type of Content the server returns to the client.
Content-Length: the Length of the Content (such as the file size) that the server returns to the client)
3. entity content (response body)
The specific data that the server returns to the client, such as file data.
NSMutableURLRequest (Note: Non-NSURLRequest because this object is immutable)
1. Set the timeout time (60 s by default)
Request. timeoutInterval = 15;
2. Set the Request Method
Request. HTTPMethod = @ "POST ";
3. Set the Request body
Request. HTTPBody = data;
4. Set the request header. For example, set the header for transmitting JSON data.
[Request setValue: @ "application/json" forHTTPHeaderField: @ "Content-Type"];
GET and POST comparison:
GET (get request by default ):
Features: parameters submitted in GET mode are directly spliced to the url request address. Multiple parameters are separated. For example: http: // localhost: 8080/myService/login? Username = 123 & pwd = 123
Disadvantages:
1. All request data is exposed in the url, which is not safe.
2. Because the browser and server have restrictions on the URL length, the parameters attached to the URL are limited. Generally, the length cannot exceed 1 kb.
-(IBAction) login {NSString * loginUser = self. userName. text; NSString * loginPwd = self. pwd. text; if (loginUser. length = 0) {[MBProgressHUD showError: @ "Enter the user name! "]; Return;} if (loginPwd. length = 0) {[MBProgressHUD showError: @" enter the password! "]; Return;} // Add the mask [MBProgressHUD showMessage: @" logging in ..... "]; // The default is get request: get parameters are directly spliced into the url NSString * urlStr = [NSString stringWithFormat: @" http: // localhost: 8080/myService/login? Username = % @ & pwd = % @ ", loginUser, loginPwd]; // post request. Put parameters in the Request body // NSString * urlStr = @" http: // localhost: 8080/myService/login "; // URL transcoding urlStr = [urlStr encoding: [NSCharacterSet URLQueryAllowedCharacterSet]; // urlStr = [urlStr encoding: NSUTF8StringEncoding]; NSURL * url = [NSURL URLWithString: urlStr]; NSMutableURLRequest * reques T = [NSMutableURLRequest requestWithURL: url]; // set the timeout time (60 s by default) request. timeoutInterval = 15; // set the request method. HTTPMethod = @ "POST"; // set the Request body NSString * param = [NSString stringWithFormat: @ "username =%@ & pwd =%@", loginUser, loginPwd]; // NSString --> NSData request. HTTPBody = [param dataUsingEncoding: NSUTF8StringEncoding]; // set the request header information [request setValue: @ "iphone" forHTTPHeaderField: @ "User-Agent"]; [NSURLCo Nnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {// hide the mask [MBProgressHUD hideHUD]; if (connectionError | data = nil) {[MBProgressHUD showError: @ "Network busy! Try again later! "]; Return;} else {NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: nil]; NSString * error = dict [@" error "]; if (error) {[MBProgressHUD showError: error];} else {NSString * success = dict [@ "success"]; [MBProgressHUD showSuccess: success] ;}}];}
POST
Features:
1. Place all Request Parameters in the HTTP body
2. Theoretically, there is no limit on the size of data sent to the server.
3. relatively secure request data (no absolute security)
// 1.URL NSURL * url = [NSURL URLWithString: @ "http: // localhost: 8080/myService/order"]; NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; request. timeoutInterval = 15; request. HTTPMethod = @ "POST"; NSDictionary * orderInfo = @ {@ "shop_id": @ "1111", @ "shop_name": @ "", @ "user_id ": @ "8919"}; NSData * json = [NSJSONSerialization dataWithJSONObject: orderInfo options: NSJSONWri TingPrettyPrinted error: nil]; request. HTTPBody = json; // 5. set request Header: the data in the request body is no longer a common parameter, but a JSON data [request setValue: @ "application/json" forHTTPHeaderField: @ "Content-Type"]; [NSURLConnection failed: request queue: [NSOperationQueue mainQueue] completionHandler: ^ (NSURLResponse * _ Nullable response, NSData * _ Nullable data, NSError * _ Nullable connectionError) {if (connectionError | data = = Nil) {[MBProgressHUD showError: @ "Network busy! Try again later! "]; Return;} else {NSDictionary * dict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableLeaves error: nil]; NSString * error = dict [@" error "]; if (error) {[MBProgressHUD showError: error];} else {NSString * success = dict [@ "success"]; [MBProgressHUD showSuccess: success] ;}}];
Url transcoding problem (the URL cannot contain Chinese characters)
1. This method is out of date
NSString * urlStr = [NSString stringWithFormat: @ "http: // localhost/login? Username = & pwd = 123 "]; urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
2. Recommended official use:
NSString * urlStr = [NSString stringWithFormat: @ "http: // localhost/login? Username = drinking & pwd = 123 "]; urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet];