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;
}

 

解決方案二:html

  構建請求參數,設置HTTPBody,直接操做request:json

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];
相關文章
相關標籤/搜索