HTTPDataProcession.m 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. //
  2. // HTTPDataProcession.m
  3. // Unity-iPhone
  4. //
  5. // Created by duowan123 on 2021/2/2.
  6. //
  7. #import "HTTPDataProcession.h"
  8. #define RequestSerializerType_JSON @"application/json"
  9. #define RequestSerializerType_URLEncoded @"application/x-www-form-urlencoded"
  10. #define RequestSerializerType_FormData @"form-data"
  11. @interface HTTPDataProcession ()<NSURLSessionDataDelegate>
  12. @end
  13. @implementation HTTPDataProcession
  14. #pragma mark - 网络请求数据
  15. /// 向网络请求数据
  16. + (void)getHTTPDataProcession:(NSString*)urlString token:(NSString*)token success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
  17. // 1.创建url
  18. // 请求一个网页
  19. // NSString *urlString = @"http://test-shoes-api.hiyd.com/forum/friends?limit=1000";
  20. // 一些特殊字符编码
  21. urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  22. NSURL *url = [NSURL URLWithString:urlString];
  23. // 2.创建请求 并:设置缓存策略为每次都从网络加载 超时时间30秒
  24. NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
  25. //2.创建一个 NSMutableURLRequest 添加 header
  26. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  27. [mutableRequest addValue:token forHTTPHeaderField:@"token"];
  28. [mutableRequest addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
  29. //3.把值覆给request
  30. request = [mutableRequest copy];
  31. // 3.采用苹果提供的共享session
  32. NSURLSession *sharedSession = [NSURLSession sharedSession];
  33. // 4.由系统直接返回一个dataTask任务
  34. NSURLSessionDataTask *dataTask = [sharedSession dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
  35. if (data && (error == nil)){
  36. // 网络请求完成之后就会执行,NSURLSession自动实现多线程
  37. successBlock(data);
  38. } else {
  39. // 网络访问失败
  40. for (NSString * key in error.userInfo){
  41. if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
  42. id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1 error:nil];
  43. NSLog(@"错误信息 ERROR =========== >>> %@",error);
  44. failBlock(errorObject);
  45. }
  46. }
  47. }
  48. }];
  49. // 5.每一个任务默认都是挂起的,需要调用 resume 方法
  50. [dataTask resume];
  51. }
  52. /// 向网络请求数据
  53. + (void)uploadHTTPDataWithUrlString:(NSString *)urlString withParams:(NSDictionary *)params token:(NSString*)token success:(SuccessBlock)successBlock fail:(FailBlock)failBlock{
  54. NSURL *url = [NSURL URLWithString:urlString];
  55. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
  56. request.HTTPMethod = @"POST";
  57. request.timeoutInterval = 10.0f;
  58. NSString *keyValueBody = [self getKeyValueStringWithDictionary:params];
  59. request.HTTPBody = [keyValueBody dataUsingEncoding:NSUTF8StringEncoding];
  60. NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
  61. sessionConfiguration.HTTPAdditionalHeaders = @{@"Content-Type":@"application/x-www-form-urlencoded;charset=utf-8",@"token":token};
  62. NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
  63. NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error){
  64. if (data && (error == nil)){
  65. // 网络请求完成之后就会执行,NSURLSession自动实现多线程
  66. successBlock(data);
  67. }else{
  68. // 网络访问失败
  69. for (NSString * key in error.userInfo){
  70. if ([key isEqualToString:@"com.alamofire.serialization.response.error.data"]){
  71. id errorObject = [NSJSONSerialization JSONObjectWithData:error.userInfo[key] options:1 error:nil];
  72. failBlock(errorObject);
  73. }
  74. }
  75. }
  76. }];
  77. //发送请求
  78. [dataTask resume];
  79. }
  80. //
  81. +(NSString*)getKeyValueStringWithDictionary:(NSDictionary*)dic{
  82. if (!dic||dic.count==0) {
  83. return @"";
  84. }
  85. NSString *result = @"";
  86. NSArray *theAllKeys = [dic allKeys];
  87. for (int i=0; i<theAllKeys.count; i++) {
  88. NSString *theKey = [theAllKeys objectAtIndex:i];
  89. NSString *theValue = [dic objectForKey:theKey];
  90. if (i==0) {
  91. NSString *temp = [NSString stringWithFormat:@"%@=%@", theKey, theValue];
  92. result = [result stringByAppendingString:temp];
  93. }else {
  94. NSString *temp = [NSString stringWithFormat:@"&%@=%@", theKey, theValue];
  95. result = [result stringByAppendingString:temp];
  96. }
  97. }
  98. NSLog(@"result = %@",result);
  99. return result;
  100. }
  101. @end