gpt4 book ai didi

java - 如何作为浏览器下载文件

转载 作者:行者123 更新时间:2023-12-01 16:39:04 25 4
gpt4 key购买 nike

如果我通过浏览器保存mp3文件,第三方库正常是和他一起工作的,如果我通过HTTP摇动自己,那么第三方库和他一起工作,因为编码不正确而无法工作。

我使用这个代码

HttpGet first = new HttpGet(url);

first.addHeader("Content-Type", "audio/mpeg");

HttpResponse response = httpclient.execute(first, localContext);
InputStream instream = response.getEntity().getContent();

StringBuilder sb = new StringBuilder();
BufferedReader r = new BufferedReader(new InputStreamReader(instream));
for (String line = r.readLine(); line != null; line = r.readLine()) {
sb.append(line);
}

instream.close();
String textFile = sb.toString();

BufferedWriter out = new BufferedWriter(new FileWriter("test123.mp3"));
out.write(textFile);
out.close();

出了什么问题?

也许它编码了

最佳答案

您使用 Reader/Writer 而不是 InputStream/OutputStream 将二进制文件视为文本文件>。 BufferedReader#readLine() 吃 CRLF 字节。

只需直接将 InputStream 写入 OutputStream 即可,无需将字节修改为字符并返回并删除 CRLF 字节。您也无需再担心字符编码。

InputStream input = response.getEntity().getContent();
OutputStream output = new FileOutputStream("test123.mp3");
byte[] buffer = new byte[1024];

for (int length = 0; (length = input.read(buffer)) > -1;) {
output.write(buffer, 0, length);
}

output.close();
input.close();

另请参阅:

关于java - 如何作为浏览器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6004082/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com