YH_HTTPRequestSerializer.m 2.4 KB
//
//  YH_HTTPRequestSerializer.m
//  Yohoboys
//
//  Created by redding on 14-9-18.
//  Copyright (c) 2014年 YOHO. All rights reserved.
//

#import "YH_HTTPRequestSerializer.h"
#import "NSString+M16String.h"

@implementation YH_HTTPRequestSerializer

#pragma mark - AFURLRequestSerialization

- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request
                               withParameters:(id)parameters
                                        error:(NSError *__autoreleasing *)error
{
    NSParameterAssert(request);
    
    if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
        request = [super requestBySerializingRequest:request withParameters:nil 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) {
        NSMutableDictionary *newparameters = [NSMutableDictionary dictionaryWithDictionary:parameters];
        NSString *versionstring = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        newparameters[@"curVersion"] = versionstring;
        
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:newparameters options:(NSJSONWritingOptions)0 error:error];
        NSString *query = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        query = [query encodeToPercentEscapeString];
        
        if ([self.HTTPMethodsEncodingParametersInURI containsObject:[[request HTTPMethod] uppercaseString]]) {
            NSString *urlString = [[mutableRequest.URL absoluteString] stringByAppendingFormat:@"?parameters=%@", query];
            mutableRequest.URL = [NSURL URLWithString:urlString];
             
        } else {
            if (![mutableRequest valueForHTTPHeaderField:@"Content-Type"]) {
                [mutableRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
            }
            
            query = [NSString stringWithFormat:@"parameters=%@", query];
            [mutableRequest setHTTPBody:[query dataUsingEncoding:self.stringEncoding]];
        }
    }
    
    return mutableRequest;
}

@end