iPhone应用中HTTP上传请求协议是本文要介绍的内容,最近坐了一个项目涉及到图片上传的问题,起初用到socket,但是由于比较陌生,改而用 HTTP协议做web上传,这里需要自定义HTTP协议。
HTTP协议应该注意四点:
1、初始化响应服务器地址
- NSURL *url = [NSURL URLWithString:@"http://xxx.xxx.xx.xxx/mqupload.jsp"];
- [urlRequest setValue: [NSString stringWithFormat:@"%@\r\n", @"http://XXXXXX HTTP/1.1"]]; //可要可无
2、设置提交方法 GET/POST
- [urlRequest setHTTPMethod:@"POST"];
3、设置响应内容类型
- [urlRequest setValue: [NSString stringWithFormat:@"multipart/form-data;
- boundary=---------%@", @"7daaba1e0368"] forHTTPHeaderField:@"Content-Type"];
4、设置响应内容
- NSMutableData *postData = [NSMutableData dataWithCapacity:[m_imageData length]];
- [postData appendData: [[NSString stringWithFormat:@"---------%@\r\n", @"7daaba1e0368"]
- dataUsingEncoding:NSUTF8StringEncoding]];//开始标志
- [postData appendData: [[NSString stringWithFormat: @"Content-Disposition:form-data; name="File1";
- filename="1.jpg"\r\n Content-type: image/pjpeg\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];//name是页面文件的参数,type是文件类型
- [postData appendData:imageData];// 文件数据
- [postData appendData: [[NSString stringWithFormat:@"\r\n---------%@--\r\n", @"7daaba1e0368"]
- dataUsingEncoding:NSUTF8StringEncoding]];// 文件结束标志
- [urlRequest setHTTPBody:postData];//把数据加载到响应的文件体
只要做到以上几点,一个完整的http请求协议就做好了。
下面附一个简洁版完整的请求协议体
- NSURL *url = [NSURL URLWithString:@"http://XX.XX.XX"];//请求服务器路径。
- m_imageData = UIImagePNGRepresentation(myImageView.image);
- NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
- [urlRequest setHTTPMethod:@"POST"];
- [urlRequest setValue: [NSString stringWithFormat:@"multipart/form-data; boundary=---------%@",
- @"7daaba1e0368"] forHTTPHeaderField:@"Content-Type"];
- [urlRequest setValue: [NSString stringWithFormat:@"%@\r\n\r\n",
- @" keep-alive"] forHTTPHeaderField:@"Connection"];
- NSMutableData *postData = [NSMutableData dataWithCapacity:[m_imageData length]];
- [postData appendData: [[NSString stringWithFormat:@"---------%@\r\n",
- @"7daaba1e0368"] dataUsingEncoding:NSUTF8StringEncoding]];
- [postData appendData: [[NSString stringWithFormat:
- @"Content-Disposition:form-data; name="File1"; filename="1.jpg"\r\n Content-type:
- image/pjpeg\r\n\r\n"]dataUsingEncoding:NSUTF8StringEncoding]];
- [postData appendData:m_imageData];
- [postData appendData: [[NSString stringWithFormat:@"\r\n---------%@--\r\n", @"7daaba1e0368"]
- dataUsingEncoding:NSUTF8StringEncoding]];
- [urlRequest setHTTPBody:postData];
- NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
小结:详解iPhone应用中HTTP上传请求协议的内容介绍完了,主要是http上传请求协议的一个小总结,***希望本文对你有所帮助!