YH_HTTPRequestSerializer.m
2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
//
// 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