【问题标题】:How to add Headers to Request in AfNetworking 3.0?如何在 AfNetworking 3.0 中向请求添加标头?
【发布时间】:2017-03-16 05:19:22
【问题描述】:

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

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

这就是我应该将标头添加到 MutableURLRequest 的方式吗?

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

我目前遇到上述错误。

【问题讨论】:

    标签: ios objective-c afnetworking-3


    【解决方案1】:

    发现问题。

    “服务器拒绝为请求提供服务,因为请求实体的格式不受所请求方法的请求资源支持。”

    也就是说,服务器不支持application/json。

    我刚刚删除了这两行,它起作用了......

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

    【讨论】:

      【解决方案2】:

      我建议你写这样的代码,

      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")
                      }
                  }
              }
      
          }
      

      【讨论】:

        猜你喜欢
        • 2013-10-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-15
        • 1970-01-01
        • 2018-10-08
        • 1970-01-01
        相关资源
        最近更新 更多