標籤:
標題中的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 stubresponse.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 stubrequest.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 stubresponse.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 stubrequest.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裡面,安全性高,不易被捕獲;
iOS開發-Get請求,Post請求,同步請求和非同步請求