標題中的Get和Post是請求的兩種方式,同步和異步屬於實現的方法,Get方式有同步和異步兩種方法,Post同理也有兩種。稍微有點Web知識的,對Get和Post應該不會陌生,常說的請求處理響應,基本上請求的是都是這兩個哥們,Http最開始定義的與服務器交互的方式有八種,不過隨着時間的進化,如今基本上使用的只剩下這兩種,有興趣的能夠參考本人以前的博客Http協議中Get和Post的淺談,iOS客戶端須要和服務端打交道,Get和Post是跑不了的,本文中包含iOS代碼和少許Java服務端代碼,開始正題吧.html
Get和Post同步請求的時候最多見的是登陸,輸入各類密碼才能看到的功能,必須是同步,異步在Web上局部刷新的時候用的比較多,比較耗時的時候執行異步請求,可讓客戶先看到一部分功能,而後慢慢刷新,舉個例子就是餐館吃飯的時候點了十幾個菜,給你先上一兩個吃着,以後給別人上,剩下的慢慢上。大概就是這樣的。弄了幾個按鈕先上圖:java
先貼下同步請求的代碼:緩存
//設置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(忽略本地緩存);app
NSURLRequestReloadIgnoringLocalAndRemoteCacheData(無視任何緩存策略,不管是本地的仍是遠程的,老是從原地址從新下載);異步
NSURLRequestReturnCacheDataElseLoad(首先使用緩存,若是沒有本地緩存,才從原地址下載);
async
NSURLRequestReturnCacheDataDontLoad(使用本地緩存,從不下載,若是本地沒有緩存,則請求失敗,此策略多用於離線操做);post
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請求"); } }
效果以下:
異步實現的時候須要實現協議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請求"); } } }
①同步請求一旦發送,程序將中止用戶交互,直至服務器返回數據完成,才能夠進行下一步操做(例如登陸驗證);
②異步請求不會阻塞主線程,會創建一個新的線程來操做,發出異步請求後,依然能夠對UI進行操做,程序能夠繼續運行;
③Get請求,將參數直接寫在訪問路徑上,容易被外界看到,安全性不高,地址最多255字節;
④Post請求,將參數放到body裏面,安全性高,不易被捕獲;