我收到使用以下代码的文件:

byte[] fileBytes;
....
JSONObject postJSON = new JSONObject();
postJSON.put("file_name", filename);
postJSON.put("client_id", clientID);
HttpPost post = new HttpPost(fileURL);
StringEntity se = new StringEntity( postJSON.toString(), "UTF-8");
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = httpClient.execute(post);
fileBytes = EntityUtils.toByteArray(response.getEntity());


使用调试器,我看到响应得到的实体长度为27136字节,这是测试文件的正确长度,但是fileBytes数组只有11470字节长。谁能告诉我为什么发生这种截断?当我尝试获取其他文件时,也会发生类似的截断,因此它不是特定文件或特定文件长度的函数。

使用以下代码,我为同一文件得到11997字节:

StringBuilder stringBuilder = new StringBuilder("");
stringBuilder.append(EntityUtils.toString(response.getEntity()));
fileBytes = stringBuilder.toString().getBytes();


从InputStream读取,我得到12288个字节:

fileBytes = new byte[1024];
InputStream inputStream = response.getEntity().getContent();
int bytesRead = 0;
while(true){
    bytesRead = inputStream.read(fileBytes);
    if (bytesRead <= 0)
        break;
....
}


将编码更改为UTF-16会收到内部服务器错误。

我还尝试了以下方法:

InputStream inputStream = response.getEntity().getContent();
response.getEntity().getContentLength()];
while ((getByte = inputStream.read()) != -1) {
    bos.write(getByte);
}
bos.close();


这也给了我11470的文件。

在所有情况下,文件均已损坏,无法打开。在二进制文件查看器中比较时,fir 11个字节匹配,然后文件发散。我在损坏的文件中找不到任何模式。

最佳答案

好的,答案显然是以上所有都很好。问题出在服务器上,它无法正确配置数据流:Content-type是所有文件的文本/纯文本,而不是application / pdf,依此类推。

我的第一个线索是当我们在服务器上放置一个文本文件时,它成功通过。那时我开始在服务器端工作,我们很快就发现了这一点。

底线是,如果您正在处理服务器/客户端应用程序,则问题可能不在您身边。

我应该提到各种帖子,这些帖子可以帮助我构建上面收集的各种版本:

including this

and this

我向其他各种有用的人表示歉意,我也看过他们的文章并对其进行了投票。

07-24 09:49
查看更多