AfNetworking 3.0如何在Request中添加Headers?

How to add Headers to Request in AfNetworking 3.0?

我对在 'AFNetworking 3.0' 中添加 headers 感到困惑。在以前的版本中,有一个称为 RequestSerializer 的函数。如何将特定 headers 添加到可变请求?

{ 
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

 NSString *path = [[NSBundle mainBundle] pathForResource:@"uploadedImage_3" ofType:@"jpg"];
[formData appendPartWithFileURL:[NSURL fileURLWithPath:path] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} 
error:nil];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"8b10056e-59e6-4d2b-aa4f-b08f8afff80a" forHTTPHeaderField:@"session_key"];
[request addValue:@"0" forHTTPHeaderField:@"resume_key"];

AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];

NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
            uploadTaskWithStreamedRequest:request
            progress:^(NSProgress * _Nonnull uploadProgress) {
              // This is not called back on the main queue.
              // You are responsible for dispatching to the main queue for UI updates
              dispatch_async(dispatch_get_main_queue(), ^{
                //Update the progress view
                [_progressView setProgress:uploadProgress.fractionCompleted];
              });
            }
            completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
              if (error) {
                NSLog(@"Error: %@", error);
              } else {
                NSLog(@"%@ %@", response, responseObject);
              }
            }];

[uploadTask resume];
}

这是我应该将 headers 添加到 MutableURLRequest 的方式吗?

NSLocalizedDescription = Request failed: unsupported media type (415)}

我目前遇到与上述类似的错误。

找到问题。

"The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method."

换句话说,服务器不支持application/json。

我刚刚删除了这两行并且它有效...

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

我建议你这样写代码,

func apiRequest(method:String, urlMethod:String, parametersDictionary:NSMutableDictionary, success:@escaping successDictionaryBlock, failure: @escaping failBlockErrorMessage){
        let requestUrl = @“www.requestUrl”

        let headerString = "\("Bearer") \(request Token)”
        let headers: HTTPHeaders = [
            "Authorization": headerString,

            ]

        Alamofire.request(requestUrl, method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if(response.result.error == nil){

                if((response.response?.statusCode)! < 500){

                    if(response.response?.statusCode == 200){

                        if let JSON = response.result.value {

                            let dict = JSON as! NSDictionary

                            let status :Bool = dict["status"] as! Bool

                            if(status){
                                success(dict)

                            }else{
                                failure(dict["message"] as! String)
                            }

                        }
                    }else{
                        failure("Something went wrong please try again")
                    }
                }else{
                    failure("Something went wrong please try again")
                }
            }
        }

    }