關(guān)鍵代碼記錄
NSDictionary *params = @{@"type" : @"1"};
GODebugLog(@"path : %@", path);
/// ********************************************************************************
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: path] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
// 1、組裝 http body ===================
// ①定義分界線(boundary)
NSString *boundaryID = [[NSString stringWithFormat:@"boundary_cba_cfrdce_%@_%@", @(arc4random()), @(arc4random())] md5]; // 分界線標識符
NSString *boundary = [NSString stringWithFormat:@"--%@", boundaryID]; // 分界線
NSString *boundaryEnding = [NSString stringWithFormat:@"--%@--", boundaryID]; // 分界線結(jié)束
// ②圖片data
NSData *imgData = UIImageJPEGRepresentation(pic, 0.5);
// ③http body的字符串
NSMutableString *bodyString = [NSMutableString string];
// 遍歷keys,組裝文本類型參數(shù)
NSArray *keys = [params allKeys];
for (NSString *key in keys) {
// 添加分界線聊浅,換行
[bodyString appendFormat:@"%@\r\n", boundary];
// 添加參數(shù)名稱奏瞬,換2行
[bodyString appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key];
// 添加參數(shù)的值,換行
[bodyString appendFormat:@"%@\r\n", [params objectForKey:key]];
}
// 添加分界線侄刽,換行
[bodyString appendFormat:@"%@\r\n", boundary];
// 組裝文件類型參數(shù), 換行
NSString *fileParamName = @"file"; // 文件參數(shù)名
NSString *filename = @"avatar.jpg"; // 文件名
[bodyString appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fileParamName, filename];
// 聲明上傳文件的格式衷模,換2行
NSString *fileType = @"image/jpeg";
[bodyString appendFormat:@"Content-Type: %@\r\n\r\n", fileType];
// 聲明 http body data
NSMutableData *bodyData = [NSMutableData data];
// 將 body 字符串 bodyString 轉(zhuǎn)化為UTF8格式的二進制數(shù)據(jù)
NSData *bodyParamData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
[bodyData appendData:bodyParamData];
// 將 image 的 data 加入
[bodyData appendData:imgData];
[bodyData appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; // image數(shù)據(jù)添加完后 加一個換行
// 分界線結(jié)束符加入(以 NSData 形式)
NSString *boundryEndingWithReturn = [NSString stringWithFormat:@"%@\r\n", boundaryEnding]; // 分界線結(jié)束符加換行
NSData *boundryEndingData = [boundryEndingWithReturn dataUsingEncoding:NSUTF8StringEncoding];
[bodyData appendData:boundryEndingData];
// 設(shè)置 http body data
request.HTTPBody = bodyData;
// 組裝 http body 結(jié)束 ===================
// 設(shè)置 http header 中的 Content-Type 的值
NSString *content = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundaryID];
[request setValue:content forHTTPHeaderField:@"Content-Type"];
// 設(shè)置 Content-Length
[request setValue:[NSString stringWithFormat:@"%@", @(bodyData.length)] forHTTPHeaderField:@"Content-Length"];
// 設(shè)置請求方式 POST
request.HTTPMethod = @"POST";
// 三種方式都可以發(fā)起請求
#if 0 // NSURLConnection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
GODebugLog(@"response : %@", response);
GODebugLog(@"data : %@", data);
GODebugLog(@"connectionError : %@", connectionError);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"dic : %@", dic);
success(dic);
}];
#elif 1 // NSURLSessionUploadTask
NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:bodyData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
GODebugLog(@"data : %@", data);
GODebugLog(@"response : %@", response);
GODebugLog(@"error : %@", error);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"dic : %@", dic);
success(dic);
}];
[uploadTask resume];
#else // NSURLSessionDataTask
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
GODebugLog(@"data : %@", data);
GODebugLog(@"response : %@", response);
GODebugLog(@"error : %@", error);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"dic : %@", dic);
success(dic);
}];
[dataTask resume];
#endif
前一種方式拼接方式為將所有參數(shù)及參數(shù)的值(除去文件參數(shù))拼接成一個NSString鹊汛,然后再一起轉(zhuǎn)換為NSData,也可以將每一個參數(shù)和參數(shù)值分別轉(zhuǎn)換為NSData阱冶,逐個將NSData拼接到一起刁憋,兩種方式結(jié)果是一致的。
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];
NSString *boundaryID = [[NSString stringWithFormat:@"boundary_cba_cfrdce_%@_%@", @(arc4random()), @(arc4random())] md5]; // 分界線標識符
// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundaryID];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];
// post body
NSMutableData *body = [NSMutableData data];
// add params (all params are strings)
for (NSString *param in params) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundaryID] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"%@\r\n", [params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}
if (imageData) {
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundaryID] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"file"] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundaryID] dataUsingEncoding:NSUTF8StringEncoding]];
// setting the body of the post to the reqeust
[request setHTTPBody:body];
// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
// set URL
[request setURL:[NSURL URLWithString: path]];
// 三種方式都可以發(fā)起請求
#if 0 // NSURLConnection
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
GODebugLog(@"response : %@", response);
GODebugLog(@"data : %@", data);
GODebugLog(@"connectionError : %@", connectionError);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"dic : %@", dic);
success(dic);
}];
#elif 1 // NSURLSessionUploadTask
NSURLSessionUploadTask *uploadTask = [[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:bodyData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
GODebugLog(@"data : %@", data);
GODebugLog(@"response : %@", response);
GODebugLog(@"error : %@", error);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"dic : %@", dic);
success(dic);
}];
[uploadTask resume];
#else // NSURLSessionDataTask
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
GODebugLog(@"data : %@", data);
GODebugLog(@"response : %@", response);
GODebugLog(@"error : %@", error);
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"dic : %@", dic);
success(dic);
}];
[dataTask resume];
#endif