How to set HTTP request body using AFNetwork's AFHTTPRequestOperationManager?

前端 未结 7 1869
死守一世寂寞
死守一世寂寞 2020-12-13 14:49

I am using AFHTTPRequestOperationManager (2.0 AFNetworking library) for a REST POST request. But the manager only have the call to set the parameters.

-((         


        
7条回答
  •  余生分开走
    2020-12-13 15:40

    You could create your own custom subclass of AFHTTPRequestSerializer, and set this as the requestSerializer for your AFHTTPRequestOperationManager.

    In this custom requestSerializer, you could override

    - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request         
                                   withParameters:(id)parameters 
                                            error:(NSError *__autoreleasing *)error;
    

    Inside your implementation of this method, you'll have access to the NSURLRequest, so you could do something like this

    - (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request     
                                   withParameters:(id)parameters 
                                            error:(NSError *__autoreleasing *)error  
    {    
        NSURLRequest *serializedRequest = [super requestBySerializingRequest:request withParameters:parameters
         error:error];
        NSMutableURLRequest *mutableRequest = [serializedRequest mutableCopy];          
        // Set the appropriate content type
        [mutableRequest setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];              
        // 'someString' could eg be passed through and parsed out of the 'parameters' value
        NSData *httpBodyData = [someString dataUsingEncoding:NSUTF8StringEncoding];
        [mutableRequest setHTTPBody:httpBodyData];
    
        return mutableRequest;
    }
    

    You could take a look inside the implementation of AFJSONRequestSerializer for an example of setting custom HTTP body content.

提交回复
热议问题