使用 NSMutableURLRequest 通过 http post 发送文件时出现网络错误
我在使用 setHTTPBodyStream 而不是带有 NSMutableURLRequest 的 setHTTPBody 时遇到问题。
我正在编写通过 http post 将大文件发送到服务器的代码。使用以下部分代码,一切正常:
NSData * mydata = [NSData dataWithContentsOfFile:self.tmpFileLocationToUpload];
[request setHTTPBody:mydata];
如果我将其更改为:
NSData * mydata = [NSData dataWithContentsOfFile:self.tmpFileLocationToUpload];
self.tmpInputStream = [NSInputStream inputStreamWithData:mydata];
[request setHTTPBodyStream: self.tmpInputStream];
那么我总是以网络错误结束:错误 - 操作无法完成。 (kCFErrorDomainCFNetwork 错误 303。)
最后的目标是直接从文件创建 inputStrem,以便能够发送大文件而无需将它们加载到内存中。
我是否错过了 setHTTPBodyStream 使用的某些内容?
感谢您的帮助。
问候。 塞巴斯蒂安.
I have a problem using setHTTPBodyStream instead of setHTTPBody with a NSMutableURLRequest.
I'm working on code to send large file to a server through http post. With the following portion code, everything works perfectly :
NSData * mydata = [NSData dataWithContentsOfFile:self.tmpFileLocationToUpload];
[request setHTTPBody:mydata];
If I change it to :
NSData * mydata = [NSData dataWithContentsOfFile:self.tmpFileLocationToUpload];
self.tmpInputStream = [NSInputStream inputStreamWithData:mydata];
[request setHTTPBodyStream: self.tmpInputStream];
Then I always end with a network error : Error - The operation couldn’t be completed. (kCFErrorDomainCFNetwork error 303.)
The goal is at the end to create inputStrem directly from the file to be able to send large file without to load them in memory.
Did I miss something with setHTTPBodyStream use ?
Thanks for your help.
Regards.
Sébastien.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试设置 HTTP 方法(如果尚未设置)。我能够通过添加以下内容来修复“kCFErrorDomainCFNetwork error 303”错误:
Try setting the HTTP method (if you're not already). I was able to fix a "kCFErrorDomainCFNetwork error 303" error by adding:
当您使用
setHTTPBody
时,它会自动设置请求的Content-length
标头,但是当您使用setHTTPBodyStream
时,它不会,但是而是将传输编码
设置为分块
。当无法提前确定流的长度时,使用分块
传输编码。 (请参阅分块传输编码。)将
NSURLConnection
与 < code>setHTTPBodyStream,您可以手动设置Content-length
,它将阻止chunked
的Transfer-encoding
(假设您知道长度提前):使用
NSURLSession
时,尝试与分块请求一起手动设置Content-length
可能无法阻止其成为分块
要求。When you use
setHTTPBody
, it automatically sets theContent-length
header of the request, but when you usesetHTTPBodyStream
, it doesn't, but rather setsTransfer-encoding
ofchunked
. Achunked
transfer encoding is used when the length of the stream cannot be determined in advance. (See Chunked transfer encoding.)When using
NSURLConnection
in conjunction withsetHTTPBodyStream
, you can manually setContent-length
and it will prevent theTransfer-encoding
ofchunked
(assuming you know the length in advance):When using
NSURLSession
, attempts to manually setContent-length
in conjunction with a chunked request may not prevent it from being achunked
request.