how to set Content-Type other than application/json

后端 未结 1 832
小鲜肉
小鲜肉 2021-01-19 10:31

I\'m trying to send a REST API to my server by AFNetworking2.0, our server only accepts Content-Type as application/vnd.mycom.mycom-csc+json when i

相关标签:
1条回答
  • 2021-01-19 11:09

    Update: As of AFNetworking 2.2.3, all you need to do is:

    [requestSerializer setValue:@"application/vnd.mycom.mycom-csc+json" forHTTPHeaderField:@"Content-Type"];
    

    More detail in this Github issue.


    In AFNetworking 2, serialization has been abstracted out into "request serializers" and "response serializers". The classes are designed to be subclassed to handle any special cases like yours.

    For your specific question, the simplest approach would be:

    1. Create a subclass of AFJSONRequestSerializer.
    2. Override the method that generates the URL Request like so:

      - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                                     withParameters:(id)parameters
                                              error:(NSError *__autoreleasing *)error {
          NSMutableURLRequest *mutableRequest = [[super requestBySer…etc.] mutableCopy];
          [mutableRequest setValue:@"application/vnd.mycom.mycom-csc+json" forHTTPHeaderField:@"Content-Type"];
          return mutableRequest;
      }
      
    3. Tell your operation manager to use your newly created subclass:

      operationMgr.requestSerializer = [MyAwesomeJSONRequestSerializer serializer];
      

    I'm not sure if the behavior you're seeing is expected or not (the documentation doesn't match the implementation exactly). I opened an issue on Github to discuss it. Either way, the workaround I propose here should resolve the issue if you just want to get it working.

    0 讨论(0)
提交回复
热议问题