iOS 表单 application/x-www-form-urlencoded

通常客户端上传数据与服务器交互的格式是 application/json ,很简单。

application/x-www-form-urlencoded ,这种格式的数据,和json有一些区别,数据简单的处理如下

+ (NSString *)postDataWithDic:(NSDictionary *)dic
                          str:(NSMutableString *)dataStr
{
    for (int i = 0; i < dic.count;  i ++) {
        NSString *key = dic.allKeys[i];
        id value = dic[key];
        
        if ([value isKindOfClass:[NSString class]]) {
            [dataStr appendFormat:@"%@=%@&",key,value];
        }else if([value isKindOfClass:[NSDictionary class]]){
            
            NSDictionary *param = value;
            NSError *parseError = nil;
            NSData *jsonData = [NSJSONSerialization dataWithJSONObject:param options:NSJSONWritingPrettyPrinted error:&parseError];
            NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
            [dataStr appendFormat:@"%@=%@&",key,jsonString];
        }
    }
    
    NSString *postStr = [dataStr substringWithRange:NSMakeRange(0, dataStr.length - 1)];
    return postStr;
}

数据格式:title=test&content=1&subContent=2&subTitle=3

具体介绍

传送门

 

posted on 2020-09-29 16:17  金字塔上D蜗牛  阅读(1739)  评论(0编辑  收藏  举报

导航