標題中的Get和Post是請求的兩種方式,同步和異步屬於實現的方法,Get方式有同步和異步兩種方法,Post同理也有兩種。稍微有點Web知識的,對Get和Post應該不會陌生,常說的請求處理響應,基本上請求的是都是這兩個哥們,Http最開始定義的與服務器交互的方式有八種,不過隨着時間的進化,現在基本上使用的只剩下這兩種,有興趣的可以參考本人之前的博客Http協議中Get和Post的淺談,iOS客戶端需要和服務端打交道,Get和Post是跑不了的,本文中包含iOS代碼和少量Java服務端代碼,開始正題吧.
Get和Post同步請求
Get和Post同步請求的時候最常見的是登錄,輸入各種密碼才能看到的功能,必須是同步,異步在Web上局部刷新的時候用的比較多,比較耗時的時候執行異步請求,可以讓客戶先看到一部分功能,然后慢慢刷新,舉個例子就是餐館吃飯的時候點了十幾個菜,給你先上一兩個吃着,之后給別人上,剩下的慢慢上。大概就是這樣的。弄了幾個按鈕先上圖:
先貼下同步請求的代碼:
//設置URL路徑 NSString *urlStr=[NSString stringWithFormat:@"http://localhost:8080/MyWeb/Book?username=%@&password=%@&type=get",@"博客園",@"keso"]; urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr]; //通過URL設置網絡請求 NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; NSError *error=nil; //獲取服務器數據 NSData *requestData= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; if (error) { NSLog(@"錯誤信息:%@",[error localizedDescription]); }else{ NSString *result=[[NSString alloc]initWithData:requestData encoding:NSUTF8StringEncoding]; NSLog(@"返回結果:%@",result); }
代碼很多,需要解釋一下:
①URL如果有中文無法傳遞,需要編碼一下:
[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
②設置網路請求中的代碼,有兩個參數,最后一個設置請求的時間,這個不用說什么,重點說下緩存策略cachePolicy,系統中的定義如下:
typedef NS_ENUM(NSUInteger, NSURLRequestCachePolicy) { NSURLRequestUseProtocolCachePolicy = 0, NSURLRequestReloadIgnoringLocalCacheData = 1, NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4, // Unimplemented NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData, NSURLRequestReturnCacheDataElseLoad = 2, NSURLRequestReturnCacheDataDontLoad = 3, NSURLRequestReloadRevalidatingCacheData = 5, // Unimplemented };
NSURLRequestUseProtocolCachePolicy(基礎策略),NSURLRequestReloadIgnoringLocalCacheData(忽略本地緩存);
NSURLRequestReloadIgnoringLocalAndRemoteCacheData(無視任何緩存策略,無論是本地的還是遠程的,總是從原地址重新下載);
NSURLRequestReturnCacheDataElseLoad(首先使用緩存,如果沒有本地緩存,才從原地址下載);
NSURLRequestReturnCacheDataDontLoad(使用本地緩存,從不下載,如果本地沒有緩存,則請求失敗,此策略多用於離線操作);
NSURLRequestReloadRevalidatingCacheData(如果本地緩存是有效的則不下載,其他任何情況都從原地址重新下載);
Java服務端代碼:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8;"); PrintWriter out = response.getWriter(); System.out.println(request.getParameter("username")); System.out.println(request.getParameter("password")); if (request.getParameter("type") == null) { out.print("默認測試"); } else { if (request.getParameter("type").equals("async")) { out.print("異步Get請求"); } else { out.print("Get請求"); } } }
最終效果如下:
Post請求的代碼,基本跟Get類型,有注釋,就不多解釋了:
//設置URL NSURL *url=[NSURL URLWithString:@"http://localhost:8080/MyWeb/Book"]; //創建請求 NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [request setHTTPMethod:@"POST"];//設置請求方式為POST,默認為GET NSString *param= @"Name=博客園&Address=http://www.cnblogs.com/xiaofeixiang&Type=post";//設置參數 NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data]; //連接服務器 NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]; NSString *result= [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding]; NSLog(@"%@",result);
Java服務端代碼:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); System.out.println("姓名:" + request.getParameter("Name")); System.out.println("地址:" + request.getParameter("Address")); System.out.println("類型:" + request.getParameter("Type")); if (request.getParameter("Type").equals("async")) { out.print("異步請求"); } else { out.print("Post請求"); } }
效果如下:
Get和Post異步請求
異步實現的時候需要實現協議NSURLConnectionDataDelegate,Get異步代碼如下:
//設置URL路徑 NSString *urlStr=[NSString stringWithFormat:@"http://localhost:8080/MyWeb/Book?username=%@&password=%s&type=async",@"FlyElephant","keso"]; urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL *url=[NSURL URLWithString:urlStr]; //創建請求 NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; //連接服務器 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
實現協議的連接過程的方法:
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{ NSHTTPURLResponse *res = (NSHTTPURLResponse *)response; NSLog(@"%@",[res allHeaderFields]); self.myResult = [NSMutableData data]; } ////接收到服務器傳輸數據的時候調用,此方法根據數據大小執行若干次 -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.myResult appendData:data]; } //數據傳輸完成之后執行方法 -(void)connectionDidFinishLoading:(NSURLConnection *)connection { NSString *receiveStr = [[NSString alloc]initWithData:self.myResult encoding:NSUTF8StringEncoding]; NSLog(@"%@",receiveStr); } //網絡請求時出現錯誤(斷網,連接超時)執行方法 -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog(@"%@",[error localizedDescription]); }
異步傳輸的過程數據需要拼接,所以這個時候需要設置一個屬性接收數據:
@property (strong,nonatomic) NSMutableData *myResult;
效果如下:
Post異步傳遞代碼:
//設置URL NSURL *url=[NSURL URLWithString:@"http://localhost:8080/MyWeb/Book"]; //設置請求 NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10]; [request setHTTPMethod:@"POST"];//設置請求方式為POST,默認為GET NSString *param= @"Name=keso&Address=http://www.cnblogs.com/xiaofeixiang&Type=async";//設置參數 NSData *data = [param dataUsingEncoding:NSUTF8StringEncoding]; [request setHTTPBody:data]; //連接服務器 NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
效果如下:
異步的請求比較簡單,需要的方法都已經被封裝好了,需要注意數據是動態拼接的,請求的代碼都是在Java Servlet中實現的,Java項目中的目錄如下:
Book.java中代碼如下:
import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Book */ @WebServlet("/Book") public class Book extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Book() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8;"); PrintWriter out = response.getWriter(); System.out.println(request.getParameter("username")); System.out.println(request.getParameter("password")); if (request.getParameter("type") == null) { out.print("默認測試"); } else { if (request.getParameter("type").equals("async")) { out.print("異步Get請求"); } else { out.print("Get請求"); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); System.out.println("姓名:" + request.getParameter("Name")); System.out.println("地址:" + request.getParameter("Address")); System.out.println("類型:" + request.getParameter("Type")); if (request.getParameter("Type").equals("async")) { out.print("異步Post請求"); } else { out.print("Post請求"); } } }
Get和Post總結
①同步請求一旦發送,程序將停止用戶交互,直至服務器返回數據完成,才可以進行下一步操作(例如登錄驗證);
②異步請求不會阻塞主線程,會建立一個新的線程來操作,發出異步請求后,依然可以對UI進行操作,程序可以繼續運行;
③Get請求,將參數直接寫在訪問路徑上,容易被外界看到,安全性不高,地址最多255字節;
④Post請求,將參數放到body里面,安全性高,不易被捕獲;