1.NSData
NSData相当于一个GET请求
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *urlStrig = @"http://ip:port?name=张三&pwd=123";
urlStrig = [urlStrig stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlStrig];
NSData *data = [NSData dataWithContentsOfURL:url];
});
2.NSURLConnection
1>GET
参数拼接在url上
NSString *urlStrig = @"http://ip:port?name=张三&pwd=123";
urlStrig = [urlStrig stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlStrig];
NSURLRequest *request = [NSURLRequest requestWithURL:url];//默认为GET
//同步请求
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//异步请求
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
}];
一般http的GET请求使用sendAsynchronousRequest发送一个异步请求就可以完成了,如果要下载大文件最好使用代理方式来处理
//此方法会初始化一个NSURLConnection对象,并且会马上发送请求
//self遵守的代理为NSURLConnectionDataDelegate
[NSURLConnection connectionWithRequest:request delegate:self]
NSURLConnectionDataDelegate代理方法
/**
接受到服务器的响应就会调用此方法
@param response 响应,可以通过响应回去文件的大小
*/
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
}
/**
接收到服务器返回的实体数据时调用
此方法可能会被调用多次
@param data 本次返回的数据
*/
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
}
/**
所有数据接受完毕调用
通常在该方法中处理服务器返回的数据
*/
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
}
/**
请求错误时会调用
*/
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
}
2>POST
参数写在请求体中
NSString *urlStrig = @"http://ip:port/login";
urlStrig = [urlStrig stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url = [NSURL URLWithString:urlStrig];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.HTTPBody = [@"account=12345&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
}];
这里只设置普通参数,如果需要上传文件可以 参考iOS上传文件
3.NSURLSession
使用方法为获取session对象,使用session创建一个请求任务,开始任务即可。
请求任务:
NSURLSessionTask是URL会话中任务的基类,一般不直接使用,主要使用的是其子类
1>简单的http请求
1.获取NSURLSession对象
NSURLSession *session = [NSURLSession sharedSession];
2.使用session对象创建一个普通的请求任务
NSURL *url = [NSURL URLWithString:@""];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
}];
3.开启任务
[task resume];
这里只是一个简单的GET请求,如果要使用POST那就设置request就可以,代码和NSURLConnection一样
2>下载文件
参考iOS文件下载的NSURLSession部分
4.AFNetWorking
AFNetWorking是封装NSURLConnection和NSURLSession的框架
1>GET
NSMutableDictionary *param = [NSMutableDictionary dictionary];
param[@"username"] = @"张三";
param[@"age"] = @(20);
NSString *url = @"";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//请求超时时间
manager.requestSerializer.timeoutInterval = 30;
//告诉返回的数据(responseObject)为NSDictionary对象,默认为AFJSONResponseSerializer
manager.responseSerializer = [AFJSONResponseSerializer serializer];
//告诉返回的数据(responseObject)为NSXMLParser对象
//manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
//告诉返回的数据(responseObject)为原数据(NSData)
//manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:url parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
2>POST
间隔GET方法中的“GET”改为“POST”即可
3>文件上传
NSString *urlString = @"";
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
//普通参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:@"张三" forKey:@"username"];
[mgr POST:urlString parameters:params constructingBodyWithBlock:^(id formData) {
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@""]);
/**
拼接文件参数
@fileData : 要上传的文件数据
@name : 后台定义文件的参数名
@fileName : 上传到服务器的文件名称
@mimeType : 上传的文件类型
*/
[formData appendPartWithFileData:imageData name:@"file" fileName:@"text.png" mimeType:@"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
AFHTTPSessionManager和AFHTTPRequestOperationManager的使用方法基本相同