开发者

NSMutableURLRequest and "request body stream exhausted" error

开发者 https://www.devze.com 2023-01-28 05:52 出处:网络
I have a problem with http PUT request and request body as stream from file. No matter what the size of the file i get error \"NSURLErrorDomain -1021 request body stream exhausted\"

I have a problem with http PUT request and request body as stream from file.

No matter what the size of the file i get error "NSURLErrorDomain -1021 request body stream exhausted"

I know i can override this problem by implementing the method:

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

but this approach is not good as it will upload the whole file again, and 40 MB of file turns out to be 80 Mb of data transfer.

if i take the same file as NSData and set the request body it works fine.

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

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

NSURL *url = [NSURL URLWithString:[self concatenatedURLWithPath:path]];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
[req setHTTPMethod:@"PUT"];
[req setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTim开发者_如何转开发eoutInterval: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? Am i missing something?


From the looks of it, it seems that you're not setting @"Content-Length" in the header.

The way I do it is like this:

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

Either way, I was doing batch uploading and occasionally got the body stream exhaustion error. From what I could tell, the issue was that I only had few free space on the device, and the temporary files would get deleted automatically before some uploads being finished (when receiving the error I tested to check if the file was still there, and it wasn't).


I was encountering this same problem, what fixed it for me was retaining the stream then releasing it at the end of the asynchronous HTTP transaction. Doesn't seem like this should be necessary, however it got me around the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号