GET和POST请求方式的区别:
1.GET是用来从服务器上获得数据,而POST是用来向服务器上传数据。(当然POST也可以做到获取数据的功能,就是在代码里加上返回数据的语句)
2.GET将表单中的数据按照 variable=value 的形式,添加到所请求连接的URL后面,与URL之间使用“?”连接,而各个变量之间使用“&”连接;POST是将变量和值相对应后附加到请求体中,传递到请求连接的URL。
3.GET请求是不安全的,因为在传输过程中,数据被放在请求的URL中,隐私信息容易被第三方看到。而POST是将数据附加到请求体中,所有操作对用户来说都是不可见的。
4.GET方式传输的数据量小,主要因为受URL长度限制;而POST可以传输大量的数据,所以上传文件就只能使用POST方案。
5.GET一般限制请求数据的编码集必须为ASCII字符;而POST支持整个ISO10646字符集。默认是用ISO-8859-1编码。
发送同步POST请求的步骤:
- 创建NSURL
- 创建NSMutableURLRequest请求
- 请求参数转换及设置方法体
- 使用NSURLConnection发送请求
代码如下:
1.创建NSURL
NSString *urlString = @"https://api.weibo.com/2/statuses/update.json";
//字符串编码
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlString];
2.创建NSMutableURLRequest请求
NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
3.请求参数转换及设置方法体
//请求参数转化
NSString *bodyString = @"status=hahaha&access_token=2.00zMf9ND9ip3KCc14c03c2900L6tAc";
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
//设置方法体(请求体)
[mRequest setHTTPMethod:@"POST"];
[mRequest setHTTPBody:data];
4.使用NSURLConnection 发送请求
NSData *resultData = [NSURLConnection sendSynchronousRequest:mRequest returningResponse:nil error:nil];
//如果我们想要知道发出去的数据,可以解析数据并打印输出
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:resultData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dictionary = %@",dictionary);
发送异步POST请求的步骤:
1.创建NSURL
NSString *urlString = @"https://api.weibo.com/2/statuses/update.json";
//字符串编码
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlString];
2.创建 NSMutableURLRequest 请求
NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
3.请求参数转换及设置方法体
NSString *bodyString = @"status=hahaha&access_token=2.00zMf9ND9ip3KCc14c03c2900L6tAc";
NSData *data = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[mRequest setHTTPMethod:@"POST"];
[mRequest setHTTPBody:data];
4.使用NSURLConnection(代理方法)发送请求
NSURLConnection *connection = [NSURLConnection connectionWithRequest:mRequest delegate:self];
5.使用代理,即遵循协议需时需要实现的一些方法
//1.服务器开始响应,准备向客户端发送数据
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response{
NSLog(@"服务器开始响应,准备向客户端发送数据");
NSMutableData *mData = [NSMutableData data];
}
//2.从服务器接收到数据,并且此方法会执行多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data{
NSLog(@"从服务器接收到数据,并且此方法会执行多次");
[mData appendData:data];
}
//3.接收数据完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"接收数据完成");
//如果只是上传数据,以下语句可以不要
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:mData options:NSJSONReadingAllowFragments error:nil];
NSLog(@"dictionary = %@",dictionary);
}