#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];