HttpClient API 不保存大小超过 1.9 kb 的图像
我一直陷入一个奇怪的问题。 我正在使用 org.apache.http.impl.client.HttpClient api 在两个网站之间进行 XML 和媒体传输, 现在,使用 DefaultHttpClient
从网络读取二进制内容(在本例中为图像)时,仅保存 1.9 kb 的图像。 问题很奇怪,因为代码在我的开发环境(windows和ubuntu linux)上运行良好, 但只出现在我的生产环境SUSE linux上。
下面是我用来保存文件的代码。
HttpResponse response = defaultHttpClient.execute(request);
InputStream stream = response.getEntity().getContent();
byte[] buffer = new byte[10024];
int count = stream.read(buffer);
buffer = Arrays.copyOf(buffer, count);
FileOutputStream fstream = new FileOutputStream("myFile.jpeg",true);
fstream.write(buffer, 0, count);
fstream.flush();
fstream.close();
stream.close();
任何帮助将不胜感激。
谢谢
沙伊莱什。
I have been stucked in a strange problem.
I am using org.apache.http.impl.client.HttpClient
api for an XML and media transfer beetween two web sites,
now while reading a binary content (image in my case) from the web using DefaultHttpClient
only 1.9 kb of the image is saved.
The problem is strange because the code works fine on my development environment (windows and ubuntu linux),
but appears only on my production environment that is SUSE linux.
below is the code i have used to save the file.
HttpResponse response = defaultHttpClient.execute(request);
InputStream stream = response.getEntity().getContent();
byte[] buffer = new byte[10024];
int count = stream.read(buffer);
buffer = Arrays.copyOf(buffer, count);
FileOutputStream fstream = new FileOutputStream("myFile.jpeg",true);
fstream.write(buffer, 0, count);
fstream.flush();
fstream.close();
stream.close();
Any help will be appreciated.
Thanks
Shailesh.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在创建字节缓冲区之前,您应该检查响应的内容长度。
其次,您应该检查变量 count 中读取了多少字节。
You should be checking for the content length of your response before creating your byte buffer.
Secondly, you should be checking to see how many bytes were read in the variable count.
您的问题是您只读取
buffer.length
数据(即10024
)字节,而没有读取其余部分。做一些这样的事情:
另外,我会在
finally
try-finally 块中关闭所有Closeable
对象(为了保证)。Your problem is you just reading your
buffer.length
data (which is10024
) bytes and you're not reading the rest.Do something of this effect:
Plus, I would close all my
Closeable
objects in afinally
try-finally block (for guarantee).从输入流中读取一些数量的字节并将它们存储到缓冲区数组 b 中。
您对 #read 方法契约的理解是错误的。无法保证 read 方法将在一次调用中检索整个响应内容,即使它非常小。必须继续从输入流读取,直到流结束(读取操作返回 -1)
Reads some number of bytes from the input stream and stores them into the buffer array b.
Your understanding of the #read method's contract is wrong. There is no guarantee that the read method will retrieve the entire response content in one invocation, even if it is really small. One must keep on reading from the input stream until the end of stream (read operation returns -1)