现在AFNetworking请求是很方便的。不过最近在做一个SDK。其实在sdk里用第三方库也是很正常的。比如极光的SDK就用了AF。只要告诉别人就行。避免重复引入。
不过这样也有一个问题,比如你用了2.0的版本。别人用了3.0的版本。这种情况其实很有可能发生,因为通常别人项目用的库是比较新的,而别人引入的一堆SDK,可能很久都不更新了。
假如3.0版本中把2.0的一个方法去掉了。这样sdk就报错了。虽然通常是会兼容,但也不排除。所以我在我的SDK里没有用到第三方库。都是用的ios原生网路请求。大部分用框架后,很多原生的东西就不再记得了。记录下:
1.先来看post请求:
//获取验证码 post ok - (void)getSmsCodeWithPhone:(NSString *) phone{ //1.确定请求路径 NSString *apiUrl = [WkUtils getSmsCodeUrl]; NSLog(@"获取验证码的Url路径是: %@,传递的参数phone= %@",apiUrl,phone); NSURL *url = [NSURL URLWithString:apiUrl]; //2.创建请求对象 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //2.1更改请求方法 request.HTTPMethod = @"POST"; //2.2设置请求体 NSString *bodyStr = [NSString stringWithFormat:@"type=1&phone=%@",phone]; request.HTTPBody = [bodyStr dataUsingEncoding:NSUTF8StringEncoding]; //2.3请求超时 request.timeoutInterval = 10; NSURLSession *session_post = [NSURLSession sharedSession]; NSURLSessionDataTask *task_post = [session_post dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { if(error == nil) { //说明:(此处返回的数据是JSON格式的,因此使用NSJSONSerialization进行反序列化处理) //解析数据 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"获取验证码服务端返回: %@",dic); int code = [[dic objectForKey:@"code"] intValue]; if(code == 200){ } else { NSString *msg = [WkUtils getServercCodeStr:code]; NSLog(@"验证码msg is %@",msg); [self showMyAlertWithContent:msg]; } }else{ NSLog(@"出错"); [self showMyAlertWithContent:@"获取验证码出错"]; } }]; [task_post resume]; }
另外一个就是上传文件的,包括上传图片,这个功能经常用到,比如换头像什么的。
- (void)originalUploadFileWithImgName:(NSString *)imgName andImgData:(NSData *)imgData{ NSDictionary *params = @{@"address" : @"xxxx", @"userName" : @"FlyElephant"}; // NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"jpg"]; NSString *boundary = [self generateBoundaryString]; // 请求的Url NSString *apiUrl = [WkUtils getUploadPicUrl]; NSLog(@"上传统头像Url路径是: %@",apiUrl); NSURL *url = [NSURL URLWithString:apiUrl]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; [request setHTTPMethod:@"POST"]; // 设置ContentType NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; // NSString *fieldName = [@"CustomFile"]; NSData *httpBody = [self createBodyWithBoundary:boundary parameters:params imgName:imgName andImgData:imgData]; NSURLSessionTask *task = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:httpBody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { if (error) { NSLog(@"error = %@", error); return; } //解析数据 NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; NSLog(@"上传文件,服务端返回: %@",dic); NSString *msg = [dic objectForKey:@"msg"] ; int code = [[dic objectForKey:@"code"] intValue]; if(code == 200){ self.picUrl = [dic objectForKey:@"data"]; NSLog(@"picUrl is %@",self.picUrl); } else { NSLog(@"msg is %@",msg); } }]; [task resume]; } - (NSData *)createBodyWithBoundary:(NSString *)boundary parameters:(NSDictionary *)parameters imgName:(NSString *)imgName andImgData:(NSData *) imgData{ NSMutableData *httpBody = [NSMutableData data]; // 文本参数 [parameters enumerateKeysAndObjectsUsingBlock:^(NSString *parameterKey, NSString *parameterValue, BOOL *stop) { [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", parameterKey] dataUsingEncoding:NSUTF8StringEncoding]]; [httpBody appendData:[[NSString stringWithFormat:@"%@\r\n", parameterValue] dataUsingEncoding:NSUTF8StringEncoding]]; }]; [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", @"file", imgName] dataUsingEncoding:NSUTF8StringEncoding]]; [httpBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", @"multipart/form-data"] dataUsingEncoding:NSUTF8StringEncoding]]; // [httpBody appendFormat:@"Content-Type: application/octet-stream\r\n\r\n"]; [httpBody appendData:imgData]; [httpBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; [httpBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; return httpBody; } - (NSString *)generateBoundaryString { return [NSString stringWithFormat:@"Boundary-%@", [[NSUUID UUID] UUIDString]]; }
是不是很麻烦,其实这些用afnetworking几句代码就可以搞定,哈哈哈。httpbody里面的那些具体数据就不说了,大家可以搜下iOS图片上传,网上有说,重要的就是\r\n代表换行