如何在 iPhone 上实现分块 http 请求?
目前,我正在尝试使用 NSMutableURLRequest,将 HTTPBody 设置为我提供此块的自定义编写的 NSInputStream。
如果不是 NSMutableURLRequest 不断要求我在 NSInputStream 类中实现越来越多的方法,这会很好。首先它要求我实现 -streamStatus: ,这实现起来相当简单,但是现在它要求 _scheduleInCFRunLoop:forMode:...
基本上我正在从算法中生成数据,并希望通过分块请求将其发送到服务器。
这是代码:
@interface GERHTTPChunkInputStream : NSInputStream
{
uint8_t counter_;
}
- (GERHTTPChunkInputStream *)init;
- (void)dealloc;
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len;
- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len;
- (BOOL)hasBytesAvailable;
- (NSStreamStatus)streamStatus;
@end
@implementation GERHTTPChunkInputStream
- (GERHTTPChunkInputStream *)init {
[super init];
return self;
}
- (void)dealloc {
assert(NO);
[super dealloc];
}
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len {
NSLog(@"Getting more bytes!!!");
for (int i = 0; i < len; ++i) {
buffer[i] = ++counter_;
}
return len;
}
- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len {
return NO;
}
- (BOOL)hasBytesAvailable {
return YES;
}
- (NSStreamStatus)streamStatus {
return NSStreamStatusNotOpen;
}
@end
Currently I'm trying to use a NSMutableURLRequest, setting the HTTPBody to a custom written NSInputStream of mine that provides this chunks.
This would be fine if it were not for the fact that NSMutableURLRequest keeps asking me to implement more and more methods in my NSInputStream class. First it asked me to implement - streamStatus: and that was rather straightforward to implement however now it's asking for _scheduleInCFRunLoop:forMode:...
Basically I'm generating data out of an algorithm and would like to send it to the server via chunked request.
Here's the code:
@interface GERHTTPChunkInputStream : NSInputStream
{
uint8_t counter_;
}
- (GERHTTPChunkInputStream *)init;
- (void)dealloc;
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len;
- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len;
- (BOOL)hasBytesAvailable;
- (NSStreamStatus)streamStatus;
@end
@implementation GERHTTPChunkInputStream
- (GERHTTPChunkInputStream *)init {
[super init];
return self;
}
- (void)dealloc {
assert(NO);
[super dealloc];
}
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len {
NSLog(@"Getting more bytes!!!");
for (int i = 0; i < len; ++i) {
buffer[i] = ++counter_;
}
return len;
}
- (BOOL)getBuffer:(uint8_t **)buffer length:(NSUInteger *)len {
return NO;
}
- (BOOL)hasBytesAvailable {
return YES;
}
- (NSStreamStatus)streamStatus {
return NSStreamStatusNotOpen;
}
@end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据网上的一些讨论,很难子类化NSInputStream。查看 使用 NSInputStream 的多部分 POST 或 NSInputStream 子类异步。
看来你确实需要实现这些奇怪的私有方法......
According to a few discussions on the net, it is difficult to subclass NSInputStream. Have a look at Multipart POST using NSInputStream or NSInputStream subclass asynchronous.
It seems that you indeed need to implement these strange private methods...