1. 程式人生 > >AFNetworking 3.0 解決加密後請求引數是字串問題

AFNetworking 3.0 解決加密後請求引數是字串問題

把整個請求引數的json加密生成一個字串傳給伺服器,錯誤提示:[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'; 因為請求引數不是字典、陣列、集合...等, AFNetworking自動過濾掉了;   解決方案一:   在AFNetworking原始碼的AFURLRequestSerialization.m修改:
#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"]; } // [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]];
if ([parameters isKindOfClass:[NSString class]]) { [mutableRequest setHTTPBody:[parameters dataUsingEncoding:NSUTF8StringEncoding]]; }else{ [mutableRequest setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:self.writingOptions error:error]]; } } return mutableRequest; }

 

解決方案二:

  構建請求引數,設定HTTPBody,直接操作request:

NSMutableURLRequest *request =
    [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    [request setHTTPMethod:@"POST"];
    
    //requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    //[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

// 此處設定請求體 (即將引數加密後的字串,轉為data)  
一般是引數字典轉json字串,再將json字串加密,最後將加密後的字串轉為data 設定為請求體

 [request setHTTPBody: [data dataUsingEncoding:NSUTF8StringEncoding]];

然後傳送請求:

requestManager = [AFHTTPSessionManager manager];
 requestManager.requestSerializer = [AFJSONRequestSerializer serializer];    requestManager.responseSerializer = [AFHTTPResponseSerializer serializer];

 NSURLSessionDataTask * tesk = [requestManager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
        
        if (error) {
            
            failure(error);
            
        }else{
            
            success(responseObject);
        }
    }];
    [tesk resume];