上传音频 - http 流



我正在尝试在流模式下在http下上传线性文件。这个想法是同时做这个步骤,1)线程1:录制音频文件并将其存储在临时文件中2) 线程 2:从临时文件中获取 n 个字节并将其发送到 http 服务器。

我怎样才能写一个http流?,在CFHTTPStream上我没有看到写法,只读了:s我需要使用插座吗?谢谢!!!

我的实际代码是

   CFWriteStreamRef stream;
   NSString *strUrl = @"myurl";       
   NSURL *url = [[[NSURL alloc] initWithString:strUrl] retain];
   CFStringRef requestMethod = CFSTR("GET");
   CFHTTPMessageRef message= CFHTTPMessageCreateRequest(kCFAllocatorDefault, requestMethod, (CFURLRef)url, kCFHTTPVersion1_1);
    CFHTTPMessageSetHeaderFieldValue(message, CFSTR("Content-Type"),
                                     CFSTR("multipart/form-data"));
   stream =  ??  //CFReadStreamCreateForHTTPRequest(NULL, message);
    CFRelease(message);
  //other headers...        
    if (CFWriteStreamSetProperty(stream, kCFStreamPropertyHTTPShouldAutoredirect, kCFBooleanTrue)  == false)
    {
        NSLog(@"Error");
        return NO;
    }

    //
    // Open the stream
    //
    if (!CFWriteStreamOpen(stream))
    {
        CFRelease(stream);
        NSLog(@"Error");
        return NO;
    }
    CFStreamClientContext context = {0, self, NULL, NULL, NULL};
    CFWriteStreamSetClient(stram, kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
                           RSWriteStreamCallBack,
                           &context);
    CFWriteStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);

解决方案是创建 NSInputStream 的子类,并实现 open、close、read、hasBytesAvailable 和 don't forget - (NSStreamStatus)streamStatus 等方法。最后一个方法是从http调用的,以了解我们是打开,关闭还是已完成(NSStreamStatusAtEnd)发送(还有其他状态,但这是最重要的)。我使用像缓冲区这样的tmp文件,因为我必须发送大量数据,但是,也许数据存储器缓冲区可能会更好。最后,我实现了使用我的自定义NSInputStream的其他类,这是代码:

    NSURL *url = [NSURL URLWithString:@"url"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req setHTTPMethod:@"POST"];
    //set headers if you have to do for example: 
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data"];
    [req setValue:contentType forHTTPHeaderField:@"Content-Type"];
    //Create your own InputStream
    instream = [[CustomStream alloc] init];
    [req setHTTPBodyStream:instream];
    //I remove instream later 
      NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
    [aConnection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
    [aConnection start]; 

相关内容

  • 没有找到相关文章

最新更新