因为AFN默认使用NSDATA进行转义,所以在参数中会把"" 这样在参数转义为""情况,所以要解决这个问题,需要单独写个Category,进行转义回来,在进行网络请求。
直接上代码,这个是一个AFJSONRequestSerializer类的类目
.h文件
#import <AFNetworking/AFNetworking.h>
@interface AFJSONRequestSerializer (APJSONRequestSerializer)
- (nullable NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
withParameters:(nullable id)parameters
error:(NSError * _Nullable __autoreleasing *)error NS_SWIFT_NOTHROW;
@end
.m 文件
#import "AFJSONRequestSerializer+ APJSONRequestSerializer.h"
@implementation AFJSONRequestSerializer (APJSONRequestSerializer)
- (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"];
}
NSString *jsonString = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error] encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:@"\\/" withString:@"/"];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
[mutableRequest setHTTPBody:jsonData];
// [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
}
return mutableRequest;
}
@end
直接使用上面代码,就可以解决备被转义的问题
网友评论