iOS 使用第三方网络请求AFNetworking 以ContentType:application/x-www-form-urlencoded上传表单时,格式为value=key&value=key&...
如果对上传的数据没有要求时,仅需要对 AFHTTPSessionManager初始化并设置contentType
AFHTTPSessionManager* mgr = [AFHTTPSessionManager manager];
mgr.requestSerializer = [AFHTTPRequestSerializer serializer];
[mgr.requestSerializer setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
若对要上传数据的格式有要求,例如某个字段排在拼接字符串的最后,这时如果仅仅把数据存入字典中再依次对元素进行拼接是做不到的,因为字典本身存储数据的位置是没有顺序的,但显示时,字典会对其进行ASCII排序,简直可怕,无论对字典怎么操作结果都无法改变里面的顺序。
于是改变想法,在AFNetworking对字典元素操作(取出元素进行拼接时),加以更改
所以,在AFURLRequestSerialization.m文件中 对
NSString * AFQueryStringFromParameters(NSDictionary *parameters)
方法进行改动
NSString * AFQueryStringFromParameters(NSDictionary *parameters) {
NSMutableArray *mutablePairs = [NSMutableArray array];
NSString *encryString;
NSString *param = @"";
for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) {
if([[pair URLEncodedStringValue] rangeOfString:@"encry"].location !=NSNotFound)//_roaldSearchText
{
encryString = [pair URLEncodedStringValue];
continue;
}
[mutablePairs addObject:[pair URLEncodedStringValue]];
}
param = [mutablePairs componentsJoinedByString:@"&"];
if (param) {
param = [param stringByAppendingString:@"XX--这里是盐--XX"];
const char *cStr = [param UTF8String];
unsigned char digest[CC_MD5_DIGEST_LENGTH];
CC_MD5( cStr, strlen(cStr), digest ); // This is the md5 call
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x", digest[i]];
param = output;
encryString = [NSString stringWithFormat:@"encry=%@",param];
}
if (encryString) {
[mutablePairs addObject:encryString];
}
NSString *endString = [mutablePairs componentsJoinedByString:@"&"];
return endString;
}
可以在其内操作时进行字符串拼接以及加密工作,这样在调用请求方法时就可以和之前一样传入对应的请求参数,在这里进行拼接等一系列操作。