NSMutableURLRequest(图片上传)

昨天做的图片上传,ASIHTTPRequestAFNetworking都封装了图片上传功能,而我现在的项目需要自定义URLRequest,剩下的用AFNetworking上传或者系统的网络请求都可以,代码是在网上看的iOS通过http post上传图片,然后自己测试无误后使用的。
创建URLRequest对象

NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:url
                                                               cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                           timeoutInterval:20];

拼接数据

//分界线的标识符
NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
//分界线 --AaB03x
NSString *MPboundary = [[NSString alloc] initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
//结束符 AaB03x--
NSString *endMPboundary = [[NSString alloc] initWithFormat:@"%@--",MPboundary];
//得到图片的data
NSData* data = UIImagePNGRepresentation(image);
//http body的字符串
NSMutableString *body = [[NSMutableString alloc] init];

//添加分界线,换行
[body appendFormat:@"%@\r\n",MPboundary];
//声明avatar字段,文件名为avatar.png。这边需要注意的是name=\"avatar\"是你服务器的域名,图片名随意
[body appendFormat:@"Content-Disposition:form-data;name=\"avatar\";filename=\"avatar.png\"\r\n"];
//声明上传文件的格式
[body appendFormat:@"Content-Type:image/png\r\n\r\n"];

//声明结束符:--AaB03x--
NSString *end = [[NSString alloc]initWithFormat:@"\r\n%@",endMPboundary];
//声明myRequestData,用来放入http body
NSMutableData *myRequestData = [NSMutableData data];
//将body字符串转化为UTF8格式的二进制
[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
//将image的data加入
[myRequestData appendData:data];
//加入结束符--AaB03x--
[myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];

//设置HTTPHeader中Content-Type的值
NSString *content = [[NSString alloc]initWithFormat:@"multipart/form-data;boundary=%@",TWITTERFON_FORM_BOUNDARY];
//设置HTTPHeader
[urlRequest setValue:content forHTTPHeaderField:@"Content-Type"];
//设置Content-Length
[urlRequest setValue:[NSString stringWithFormat:@"%ld",(long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
//设置http body
[urlRequest setHTTPBody:myRequestData];
//http method
[urlRequest setHTTPMethod:@"POST"];

网络请求对象

AFHTTPRequestOperation *operation = [[AFManager sharedClient] HTTPRequestOperationWithRequest:urlRequest success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //调用接口类解析xml
        [[AFParser sharedClient] xmlParser:responseObject Delegate:delegate Code:code Object:obj];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"RequestFailure");
        //请求失败设置代理
        if ([delegate respondsToSelector:@selector(AFRequest:Code:Object:)]) {
         [delegate AFRequest:nil Code:code Object:obj];
        }
    }];

//开启网络请求
[operation start];

你可能感兴趣的:(NSMutableURLRequest(图片上传))