NSMutableURLRequest error and request flow request error

I have a problem with an HTTP PUT request and requesting the body as a stream from a file.

No matter what file size I get, the error "NSURLErrorDomain -1021 requests the body stream is exhausted"

I know that I can override this problem by implementing a method:

-(NSInputStream*)connection:(NSURLConnection *)connection needNewBodyStream:(NSURLRequest *)request 

but this approach is not very good, since it will download the entire file again, and 40 MB of the file will turn out to be 80 MB of data transfer.

if I take the same file as NSData and set up the request body, it works fine.

I tried sending an Async request and synchronizing the same result in both.

Here is my code, simple and similar to an example from Apple:

 NSURL *url = [NSURL URLWithString:[self concatenatedURLWithPath:path]]; NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url]; [req setHTTPMethod:@"PUT"]; [req setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; [request setTimeoutInterval:DEFAULT_TIMEOUT]; [req setValue:_contentType forHTTPHeaderField:@"Content-Type"]; NSInputStream *fileStream = [NSInputStream inputStreamWithFileAtPath:_dataStreamLocation]; [req setHTTPBodyStream:fileStream]; _connection = [[NSURLConnection connectionWithRequest:req delegate:self] retain]; 

Am I doing something wrong? Did I miss something?

+4
source share
3 answers

In appearance it seems that you are not setting @ Content-Length in the header.

How do i do this:

 NSUInteger fileSize = [[[[NSFileManager defaultManager] attributesOfItemAtPath:_dataStreamLocation error:nil] objectForKey:NSFileSize] unsignedIntegerValue]; [request setValue:[NSString stringWithFormat:@"%u", fileSize] forHTTPHeaderField:@"Content-Length"]; 

In any case, I did batch download and sometimes got an error of exhausting the body stream. From what I could tell, the problem was that I had little free space on the device, and temporary files would be deleted automatically until some downloads were completed (upon receiving the error I tested to check if the file was still there, and it wasn’t).

+2
source

I ran into the same issue that fixed it for me, saving the stream and then releasing it at the end of the asynchronous HTTP transaction. It doesn't seem like it should be necessary, however it helped me solve the problem.

+1
source

This workaround works for me:

 [request setTimeoutInterval:240]; 
+1
source

All Articles