iOS 原生HTTP POST请求上传图片

今天项目里做一个上传图片等个人信息的时候,使用了第三方AFNetworking

- (AFHTTPRequestOperation *)POST:(NSString *)URLString

parameters:(id)parameters

constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block

success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success

failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;

但是一直都没有回调,服务器那边也接收不到请求,不知道怎么回事,于是写了一个原生的请求,有空再研究AF

- (void)postWithUrl:(NSString *)url params:(NSDictionary *)params imageData:(NSData *)imageData imageKeyword:(NSString *)imageKeywork fileName:(NSString *)fileName block:(void (^)(id responsObject, NSError *error))block

{

self.myBlock = block;

//创建可变请求

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];

//设置请求超时时间

[request setTimeoutInterval:60.0];

//创建HTTP body的字符串

NSMutableString *bodyString = [NSMutableString string];

//遍历所有字段

for (NSString *key in params) {

//添加分界线、换行符

[bodyString appendFormat:@"--%@\r\n",BOUNDARY];

//添加字段名称、换2行

[bodyString appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];

//添加字段的值、换行符

[bodyString appendFormat:@"%@\r\n",[params objectForKey:key]];

}

//添加分界线、换行符

[bodyString appendFormat:@"--%@\r\n", BOUNDARY];

//声明图片字段(imageKeyword为图片字段名,fileName为图片名)

[bodyString appendFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@.png\"\r\n",imageKeywork,fileName];

//声明上传文件的格式、换2行

[bodyString appendString:@"Content-Type: image/png\r\n\r\n"];

//声明结束符

NSString *endString = [NSString stringWithFormat:@"\r\n--%@--\r\n",BOUNDARY];

//声明请求data,用来放入HTTP body

NSMutableData *bodyData = [[NSMutableData alloc] init];

//将body字符串转化为UTF8格式的二进制 加入bodyData

[bodyData appendData:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];

//将图片的data 加入bodyData

[bodyData appendData:imageData];

//将结束符转化为UTF8格式的二进制 加入bodyData

[bodyData appendData:[endString dataUsingEncoding:NSUTF8StringEncoding]];

//设置HTTP Header 中 Content-Type 的值

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

//设置HTTP Header 中 Content-Length 的值

[request addValue:[NSString stringWithFormat:@"%ld",[bodyData length]] forHTTPHeaderField:@"Content-Length"];

//设置请求体

[request setHTTPBody:bodyData];

//设置请求方式(POST、GET)

[request setHTTPMethod:@"POST"];

[NSURLConnection connectionWithRequest:request delegate:self];

}

上一篇:poj-1314 Finding Rectangles


下一篇:hdu4970 Killing Monsters (差分数列)