我在将 http PUT 请求和请求正文作为来自文件的流时遇到问题.
I have a problem with http PUT request and request body as stream from file.
无论文件大小如何,我都会收到错误NSURLErrorDomain -1021 request body stream exhausted"
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
但这种方法不好,因为它会再次上传整个文件,而 40 MB 的文件原来是 80 Mb 的数据传输.
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.
如果我采用与 NSData 相同的文件并设置请求正文,它可以正常工作.
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.
这是我的代码,简单且类似于 Apple 的示例:
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 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? Am i missing something?
看样子,你好像没有在header中设置@"Content-Length".
From the looks of it, it seems that you're not setting @"Content-Length" in the header.
我的做法是这样的:
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).
这篇关于NSMutableURLRequest 和“请求主体流已用尽"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!