美文网首页iOS开发经验与技巧
AFNetworking POST时,参数是JSON时被添加&q

AFNetworking POST时,参数是JSON时被添加&q

作者: 1b3bd36d9d21 | 来源:发表于2017-08-10 11:46 被阅读15次

因为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

直接使用上面代码,就可以解决备被转义的问题

相关文章

网友评论

    本文标题:AFNetworking POST时,参数是JSON时被添加&q

    本文链接:https://www.haomeiwen.com/subject/wjqhrxtx.html