1. 程式人生 > >當POST請求是 既包含圖片二進位制 又包含字串引數 如何用原生請求(二)

當POST請求是 既包含圖片二進位制 又包含字串引數 如何用原生請求(二)

oc原生方法請求

1.oc原生請求    

    /*

     使用NSURLSession 進行網路請求的幾個步驟

     1.構造NSURL地址

     2.構造請求物件 NSURLRequest

     3.構造NSURLSessionConfiguration配置檔案,可選

     4.構造NSURLSession網路會話物件

     5.建立網路任務

     6.執行網路任務,傳送網路請求

     */

    NSString *boundary = @"_YJAYgDL082HLBJkC1laRbpjU5PlLgeJh_";//放入協議頭中隨機生成的字元,上傳檔案時用來作為分隔符

    NSURL *url = [NSURL URLWithString:@"url"];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

     //設定分隔符,必須寫

    [request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary] forHTTPHeaderField: @"Content-Type"];

    //設定POST請求

    request.HTTPMethod = @"POST";

    request.timeoutInterval = 60;

    //設定請求體

    //cinema_id=1533

    // post body

    NSMutableData *body = [NSMutableData data];

    NSMutableDictionary *param = [NSMutableDictionary dictionary];

    [param setObject:@"value1" forKey:@"param1"];

    // add params (all params are strings)

    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    //pic_source文字定義的名字

    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", @"param1"] dataUsingEncoding:NSUTF8StringEncoding]];

    //文字內容

    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [param objectForKey:@"param1"]] dataUsingEncoding:NSUTF8StringEncoding]];

    NSData *imageData = data;

    if (imageData) {

        [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

        //檔名字

        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"picture"] 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", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:body];

    NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[body length]];

    //檔案大小

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

    [request setURL:url];

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        NSString *jsonString = [NSString stringWithFormat:@"%@", dic];

        NSLog(@"返回dic:%@",jsonString);

        //獲取響應包

        //將response 轉化為一個子類的HTTPURLResponse

        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;

        //列印狀態碼

        NSLog(@"狀態碼:%li", httpResponse.statusCode);

        //獲取響應頭

        NSDictionary *responseHeader = httpResponse.allHeaderFields;

        NSLog(@"響應頭:%@", responseHeader);

    }];

    //開始網路任務

    [dataTask resume];

2.AFN請求

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    // 'multipart/form-data;'

    // 修改請求序列器 為json格式

    manager.requestSerializer = [AFJSONRequestSerializer serializer];

    // 設定請求頭裡Content-Type 為multipart/form-data;

    [manager.requestSerializer setValue:@"multipart/form-data;" forHTTPHeaderField:@"Content-Type"];

    // 設定響應序列器為http格式

    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    // 在可接受的content-Type中新增 @"text/html"

    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    // 發出POST請求parameters引數填寫非二進位制字串引數

    [manager POST:@"url" parameters:@{@"param1":@"value1"}constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {

      // 這裡拼接 圖片二進位制資料這個mimeType必須有

      [formData appendPartWithFileData:UIImageJPEGRepresentation([UIImage imageNamed:@"123.jpg"], 1.0) name:@"picture" fileName:@"123.jpg" mimeType:@"image/jpeg"];

    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        NSLog(@"111---%@",responseObject);

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

        NSLog(@"222---%@", dic);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        NSLog(@"error == %@", error);

 }];