iOS开发网络请求之表单拼接

当服务器定义的Content-Typemultipart/form-data;的时候我们使用原生的URLSession进行网络请求的时候,我们需要进行表单拼接,下面记录一下:

1、在URLRequest中设置表单分割标识

request.addValue("multipart/form-data; boundary="+"\(boundary)", forHTTPHeaderField: "Content-Type") 
 // boundary 表单分割标识
其中" boundary " 是我自己生成的一个随机字符串作为表单的分割标识

2、表单拼接。下面是我上传图片的时候所拼接的一个表单数据

swift 版本
 /*
     fileData: 文件数据
     fileName:文件名称
     params:其他的参数
     */
    func getBodyData(fileData:Data,fileName:String,params:Dictionary?)->Data{
        
        let KNewLineString = "\r\n"
        let KNewLine:Data =  KNewLineString.data(using: String.Encoding.utf8)!
        var bodyData:Data = Data()
        let Kboundary = "--" + boundary
        // 开始拼接其他参数
        if !(params?.isEmpty)! {
            for keys in params!.keys {
                bodyData.append(Kboundary.data(using: String.Encoding.utf8)!)
                bodyData.append(KNewLine)
                let keysString = "Content-Disposition: form-data; name=\""+keys+"\""
                bodyData.append(keysString.data(using: String.Encoding.utf8)!)
                bodyData.append(KNewLine)
                bodyData.append(KNewLine)
                bodyData.append((params![keys] as! String).data(using: String.Encoding.utf8)!)
                bodyData.append(KNewLine)
            }
        }
        // 开始拼接图片数据
        bodyData.append(Kboundary.data(using: String.Encoding.utf8)!)
        bodyData.append(KNewLine)
        let configString = "Content-Disposition: form-data; name=\"file\"; filename=\""+"\(fileName)"+"\""
        bodyData.append(configString.data(using: String.Encoding.utf8)!)
        bodyData.append(KNewLine)
        let contentTypeString = "Content-Type:image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg"
        bodyData.append(contentTypeString.data(using: String.Encoding.utf8)!)
        bodyData.append(KNewLine)
        bodyData.append(KNewLine)
        bodyData.append(fileData)
        bodyData.append(KNewLine)
        // 数据拼接结束
        bodyData.append(Kboundary.data(using: String.Encoding.utf8)!)
        return bodyData
    }
Objective-C 版本
/*
     fileData: 文件数据
     fileName:文件名称
     params:其他的参数
     */
- (NSData *)getBodyDataWithFileData:(NSData *)fileData fileName:(NSString *)fileName params:(NSDictionary *)params{
    NSString *KNewLineString = @"\r\n";
    NSData *KNewLine = [KNewLineString dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableData *bodyData = [[NSMutableData alloc] init];
    NSString *Kboundary = [[NSString alloc] initWithFormat:@"--%@",boundary];

    // 开始拼接其他参数
    for(NSString *keys in params.allKeys){
        [bodyData appendData:[Kboundary dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:KNewLine];
        NSString *string = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"",keys];
        [bodyData appendData:[string dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:KNewLine];
        [bodyData appendData:KNewLine];
        NSString *value = [NSString stringWithFormat:@"%@",[params valueForKey:keys]];
        [bodyData appendData:[value dataUsingEncoding:NSUTF8StringEncoding]];
        [bodyData appendData:KNewLine];
    }
    
    // 开始拼接图片数据
    [bodyData appendData:[Kboundary dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:KNewLine];
    NSString *configString = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"file\"; filename=\"%@\"",fileName];
    [bodyData appendData:[configString dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:KNewLine];
    NSString *contentTypeString = @"Content-Type:image/jpge,image/gif, image/jpeg, image/pjpeg, image/pjpeg";
    [bodyData appendData:[contentTypeString dataUsingEncoding:NSUTF8StringEncoding]];
    [bodyData appendData:KNewLine];
    [bodyData appendData:KNewLine];
    [bodyData appendData:fileData];
    [bodyData appendData:KNewLine];
    
    // 拼接数据结束
    [bodyData appendData:[Kboundary dataUsingEncoding:NSUTF8StringEncoding]];
    
    return bodyData;
}
}

随机字符串生成

swift版本
 /*
     length: 产生随机数长度
     isContainNum: 是否包含数字
     */
    func getRandomString(length:Int,isContainNum:Bool) -> String{
        var charArray:[CChar] = Array(repeating: 0, count: length)
        for index in 0.. 57 && num < 65 && isContainNum == true{
                num = num%57+48  // 过滤ASCII值为58~64之间的字符
            }else if num > 90 && num < 97 {
                num = num%90 + 65 // 过滤ASCII值为91~96之间的字符
            }
            charArray[index] = CChar(num)
        }
        return String(cString: charArray)
    }
Objective-C 版本
- (NSString *)getRandomStringWithLength:(int)length isContainNum:(BOOL)isContainNum{
    NSString *resultStr = [[NSString alloc] init];
    for (NSInteger i = 0; i< length; i++) {
        NSInteger num = isContainNum ? arc4random_uniform(75)+48:arc4random_uniform(58)+65;
        if (num > 57 && num < 65 && isContainNum){
            num = num%57+48; // 过滤ASCII值为58~64之间的字符
        }else if (num > 90 && num < 97){
            num = num%90+65;
        }
        resultStr = [resultStr stringByAppendingFormat:@"%c",num];
    }
    
    return  resultStr;
}

你可能感兴趣的:(iOS开发网络请求之表单拼接)