GET與POST請求
簡介
-
GET請求解釋及語法格式
-
POST請求簡介及語法
-
GET請求代碼
-
POST請求代碼
GET請求解釋及語法格式
:
網絡請求默認是get
網絡請求有很多種:GET查 POST改 PUT增 DELETE刪 HEAD
在平時開發中主要用的 是 get 和 post.
get 獲得數據 (獲取用戶信息)
get 請求是沒有長度限制的,真正的長度限制是瀏覽器做的,限制長度一般2k
get 請求是有緩存的,get 有冪等的算法
get http://localhost/login.php?username=jikaipeng&password=123
請求參數暴露在url里
get請求參數格式:
?后是請求參數
參數名 = 參數值
& 連接兩個參數的
POST請求解釋及語法格式
:
get請求參數格式:
?后是請求參數
參數名 = 參數值
& 連接兩個參數的
post 添加,修改數據 (上傳或修改用戶信息)
post 請求是沒有緩存的
post 也沒有長度限制,一般控制2M以內
post 請求參數不會暴漏在外面 ,不會暴漏敏感信息
請求是有:請求頭header,請求體boby(post參數是放在請求體里的)
GET請求代碼
NSString *userName = @"haha";
NSString *password = @"123";
NSString *urlString = @"http://192.168.1.68/login.php";
//防止請求體中含有中文
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//?號是請求參數 注意username和password一定要和你的php頁面的登錄id相同
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@?username=%@&password=%@",urlString,userName,password]];
//cachePolicy 緩存策略 0表示自動緩存 timeoutInterval: 默認請求時間60s,通常設置為10-30秒之間
NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:0];
// response是服務器返回信息: 里面有所用時間,服務器的型號等.....
[NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
}];
POST請求代碼
NSString *userName = @"haha";
NSString *password = @"123";
NSString *urlString = @"http://192.168.1.68/login.php";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlString];
//可變請求,因為是post請求所以要用NSMutableURLRequest
NSMutableURLRequest *requst = [NSMutableURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:10];
requst.HTTPMethod = @"POST";
NSString *bodyString = [NSString stringWithFormat:@"username=%@&password=%@",userName,password];
//POST請求不寫這個會訪問失敗-直接顯示非法請求
requst.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
}];