上一篇讲的是如何通过socket进行网络传输,实际上对于互联网上的资源,我们更多的是基于http来开发,SimpleURLConnections展示了如何基于http来进行数据传输,这里主要是讲client如何向http服务器请求和传输数据,http服务器端的实现不在此例子范围之内,实际上就是普通的http服务器。
从本例中主要能学到三点:
- 基于Get下载文件
- 基于Put上传文件
- 基于Post上传文件
首先通过URL打开Connection:
request = [NSURLRequest requestWithURL:url];
assert(request != nil);
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
assert(self.connection != nil);
然后实现NSURLConnectionDelegate来处理数据传输,其中实现下载图片到本地文件的方法如下:
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
// A delegate method called by the NSURLConnection as data arrives. We just
// write the data to the file.
{
#pragma unused(theConnection)
NSInteger dataLength;
const uint8_t * dataBytes;
NSInteger bytesWritten;
NSInteger bytesWrittenSoFar;
assert(theConnection == self.connection);
dataLength = [data length];
dataBytes = [data bytes];
bytesWrittenSoFar = 0;
do {
bytesWritten = [self.fileStream write:&dataBytes[bytesWrittenSoFar] maxLength:dataLength - bytesWrittenSoFar];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self stopReceiveWithStatus:@"File write error"];
break;
} else {
bytesWrittenSoFar += bytesWritten;
}
} while (bytesWrittenSoFar != dataLength);
}
基于Put上传文件
Put和Get类似,只不过文件上传是通过设置HTTP header来完成的:
self.fileStream = [NSInputStream inputStreamWithFileAtPath:filePath