新项目中要求把整个请求参数的json用AES加密生成一个字符串传给服务器,本人网络库用的是AFNetworking,加密后试了一下提示“The ... argument is not valid JSON”, 因为请求参数不是json AFNetworking给自动过滤掉了.查看了AFNetworking的源码,只需要找到
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
方法,做如下修改就可以了,注释掉的是源码部分,希望能帮助到更多的小伙伴!
#pragma mark - AFURLRequestSerialization
- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(id)parameters
error:(NSError *__autoreleasing *)error
{
NSParameterAssert(request);
if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
return [super requestBySerializingRequest:request withParameters:parameters error:error];
}
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[self.HTTPRequestHeaders enumerateKeysAndObjectsUsingBlock:^(id field, id value, BOOL * __unused stop) {
if (![request valueForHTTPHeaderField:field]) {
[mutableRequest setValue:value forHTTPHeaderField:field];
}
}];
if (parameters) {
if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
[mutableRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
}
// if (![NSJSONSerialization isValidJSONObject:parameters]) {
// if (error) {
// NSDictionary *userInfo = @{NSLocalizedFailureReasonErrorKey: NSLocalizedStringFromTable(@"The `parameters` argument is not valid JSON.", @"AFNetworking", nil)};
// *error = [[NSError alloc] initWithDomain:AFURLRequestSerializationErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo];
// }
// return nil;
// }
if ([parameters isKindOfClass:[NSString class]]) {
[mutableRequest setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]];
}else{
[mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
}
// NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error];
//
// if (!jsonData) {
// return nil;
// }
//
// [mutableRequest setHTTPBody:jsonData];
}
return mutableRequest;
}