All information is uploaded in utF-8 format. So the POST request configuration: [manager.requestSerializer setValue:@”application/x-www-form-urlencoded;charset=utf8″ forHTTPHeaderField:@”Content-Type”];

Base64 Encryption (GTM Tripartite Library)

/ * * GTM research transcoding * / - (nsstrings *) base64Code {/ / use utf-8 way transcoding NSData * data = [self dataUsingEncoding: NSUTF8StringEncoding allowLossyConversion:YES]; data = [GTMBase64 encodeData:data]; NSString * output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // NSLog(@"%@",output); return output; }Copy the code

Please operate:

NSDictionary * elementDict = @{@"token":[User_Def objectForKey:@"token"]? [User_Def objectForKey: @ "token"] : @ ", "/ / token @" title ": _titleTF. Text, / / title @" content ": _detailTV. Text, / / content @"startDate":startDateStr,// startDate @"endDate":endDateStr,// endDate}; / / use YYModel, get dictionary json string nsstrings * elementStr = [nsstrings dictionaryToJson: elementDict]; NSString * base64ElementStr = [elementStr base64Code]; // Concatenate the URL string NSString * urlStr = [NSString stringWithFormat:@"%@%@%@%@",Url_Header,CreateIdeaUrl,DataCodeUrl,base64ElementStr]; / / need to "utf-8" coding format, the request urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet characterSetWithCharactersInString:urlStr]]; [NetRequest_Shared POSTChineseUrl:urlStr parameters:nil success:^(id _Nullable responseObject) { NSLog(@"%@",responseObject); } failure:^(NSError * _Nonnull error) { NSLog(@"%@",error); NSLog (@"operation: %@",[error localizedDescription] ); } ];Copy the code

Network request singleton class: NetRequest

“NetRequest. H” file:

// singleton macro #define NetRequest_Shared [NetRequest sharedNetRequest] //POST中文 -(void)POSTChineseUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure; / / POST in ChineseCopy the code

“NetRequest. M” file:

// singleton + (id)sharedNetRequest {static NetRequest * NetRequest = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ netRequest = [[NetRequest alloc] initSingleton]; }); return netRequest; } - (instancetype)initSingleton { if (self = [super init]) { } return self; } //POST 英 文 -(void)POSTUrl:(NSString *)url parameters:(NSDictionary *)parameters success:(void (^)(id))success failure:(void (^)(NSError *))failure { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; manager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; / / said do not do the SSL pinning NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000); manager.requestSerializer.stringEncoding = enc; //UTF8 manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager.requestSerializer setValue:@"application/x-www-form-urlencoded;charset=utf8" forHTTPHeaderField:@"Content-Type"]; / / UTF8 type manager. ResponseSerializer = [AFJSONResponseSerializer serializer]; manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript",@"text/html", @"text/plain", nil]; manager.requestSerializer.timeoutInterval = 6; // Request timeout [manager POST: URL parameters:parameters progress:nil Success :^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { if (success) { success(responseObject); } } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { if (failure) { failure(error); } }]; }Copy the code




When using the above methods, the following two errors are reported:
  • 1. “Unterminated string at 227 of character of {\ n \” token \ “: \” eyJhc…………………………………………………………………………………………………” General: // punctuation

  • 2. The “Expected a ‘, ‘or’} ‘at 199 character of {\ n \” token \ “: \” eyJhc…………………………………………………………………………………………………” General: // Chinese characters

Json data format problem

Example: “Expected a ‘, ‘or’} ‘at 211 character of {\ n \” token \ “: \”………………………………………………………………………………………………… \”,\n \”IdeaId\” : \”29cbffc82ef54f91b004f72a421d2714\”,\n \”content\” : \”g\Ufffd\Ufffd#\Ufffd\Ufffd\U07e6\Ufffd; \Ufffd\U2dd6\Ufffd\Ufffd\Ufffdc\Ufffd\v\Ufffd\”C\Ufffd\v\Ufffd\Ufffd; \UfffdV\Ufffd\Ufffdm\U064c\Ufffd)\Ufffd”; } is usually a converted JSON string containing the “\n” string

Solution:

NSString * elementStr = [NSString dictionaryToJson:elementDict]; / / "\ n" into a decline in line "" elementStr = [elementStr stringByReplacingOccurrencesOfString: @" \ n "withString: @" "].Copy the code

Or use YYmodel to convert to a JSON string: ⭐️

NSString * elementStr = [elementDict yy_modelToJSONString]; //json connect (data)Copy the code

I tried for a long time and it didn’t work! Reason: It is useless to process strings without encrypting them! (JSON strings converted using YYModel are standard)

Instead, handle: base64 encrypted strings.




Solution: Change the irregular Base64 characters into rules

// Change irregular base64 characters to regular base64ElementStr = (NSString) *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,\ (CFStringRef)base64ElementStr,NULL,CFSTR("! * '(); : @ & = + $, /? %#[]"),kCFStringEncodingUTF8));Copy the code

Final network please operate:

NSDictionary * elementDict = @{@"token":[User_Def objectForKey:@"token"]? [User_Def objectForKey: @ "token"] : @ ", "/ / token @" title ": _titleTF. Text, @" content ": / / subject _detailTV. Text, / / content @"startDate":startDateStr,// startDate @"endDate":endDateStr,// endDate}; / / use YYModel, get dictionary json string nsstrings * elementStr = [nsstrings dictionaryToJson: elementDict]; NSString * base64ElementStr = [elementStr base64Code]; //⭐️⭐️⭐️ change the irregular base64 characters to ⭐️ port ️ base64ElementStr = (NSString) *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,\ (CFStringRef)base64ElementStr,NULL,CFSTR("! * '(); : @ & = + $, /? %#[]"),kCFStringEncodingUTF8)); // Concatenate the URL string NSString * urlStr = [NSString stringWithFormat:@"%@%@%@%@",Url_Header,CreateIdeaUrl,DataCodeUrl,base64ElementStr]; // Use utF-8 encoding format, To request urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet characterSetWithCharactersInString:urlStr]]; [NetRequest_Shared POSTChineseUrl:urlStr parameters:nil success:^(id _Nullable responseObject) { NSLog(@"%@",responseObject); } failure:^(NSError * _Nonnull error) { NSLog(@"%@",error); NSLog (@"operation: %@",[error localizedDescription] ); } ];Copy the code

This fucking problem has been going on for days! Fortunately, the project is not rushed, looking for problems for a long time! Net please steps: data dictionary — JSON string — Base64 encryption — concatenation for URL — Post request

The error is that after using GTMBase64 for base64 encryption, forget to deal with the irregular characters after base64 transcoding!! I always thought it was the JSON format! 😂 😂 😂 😂 😂 😂 😂

(2017.09.27)

goyohol’s essay