对于服务器要求Content-Type
的格式是application/x-www-form-urlencoded;charset=utf-8
,这种不常见的情况:需要将请求
参数拼接为"key1=value1&key2=value2", 然后将拼接后的字符串转为UTF8编码,包装进请求体中。
代码:
+(void)doPostRequestUrlPath:(NSString*)urlPath params:(NSDictionary*)params
target:(UIViewController*)target
afterRequest:(void(^)(NSError *error, NSDictionary *objectDic))completion {
NSURL *url = [NSURL URLWithString:urlPath];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
request.timeoutInterval = 20.0f;
NSString *keyValueBody = [HttpHelper getKeyValueStringWithDictionary:params];
request.HTTPBody = [keyValueBody dataUsingEncoding:NSUTF8StringEncoding];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = @{@"Content-Type":@"application/x-www-form-urlencoded;charset=utf-8"};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURLSessionDataTask *dataTask= [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
completion(error,nil);
}else{
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(@"%@",dict);
completion(nil,dict);
}
}];
//发送请求
[dataTask resume];
}
+(NSString*)getKeyValueStringWithDictionary:(NSDictionary*)dic {
if (!dic||dic.count==0) {
return @"";
}
NSString *result = @"";
NSArray *theAllKeys = [dic allKeys];
for (int i=0; i<theAllKeys.count; i++) {
NSString *theKey = [theAllKeys objectAtIndex:i];
NSString *theValue = [dic objectForKey:theKey];
if (i==0) {
NSString *temp = [NSString stringWithFormat:@"%@=%@", theKey, theValue];
result = [result stringByAppendingString:temp];
}else {
NSString *temp = [NSString stringWithFormat:@"&%@=%@", theKey, theValue];
result = [result stringByAppendingString:temp];
}
}
return result;
}