网络请求-请求头设置 "Content-Type":@"application/x-www-form-urlencoded;charset=utf-8"

对于服务器要求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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容