網(wǎng)絡(luò)請(qǐng)求-請(qǐng)求頭設(shè)置 "Content-Type":@"application/x-www-form-urlencoded;charset=utf-8"

對(duì)于服務(wù)器要求Content-Type的格式是application/x-www-form-urlencoded;charset=utf-8,這種不常見(jiàn)的情況:需要將請(qǐng)求
參數(shù)拼接為"key1=value1&key2=value2", 然后將拼接后的字符串轉(zhuǎn)為UTF8編碼,包裝進(jìn)請(qǐng)求體中。

代碼:

+(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);
        }
    }];
    
    //發(fā)送請(qǐng)求
    [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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容