GET和POST请求

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 请求是没有缓存的

http://localhost/login.php

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);
}];
posted @ 2016-03-18 20:56  往事亦如风  阅读(2116)  评论(0编辑  收藏  举报