Reputation: 15378
If I save an mp3 file via a browser, the third-party library is normally working with him, if I shake myself through HTTP, then the third-party library with him unable to work due to not correctly encoded.
I use this code
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();
What's wrong?
maybe it encoded
Upvotes: 0
Views: 1236
Reputation: 4122
Don't read a String for binary content. Won't work.
And here is my obligatory advertisement for the free, open-source alternative to messing around with HTTPClient or URLConnection yourself.
Resty r = new Resty();
File f = r.bytes(url).save(new File("test123.mp3"));
Resty is available here http://beders.github.com/Resty (DISCLAIMER: I'm the maintainer of this little side project)
Upvotes: 0
Reputation: 1047
I think that your problem relies on the fact that you are writing your file as a Character file, not a binary one. Try reading this http://www.java2s.com/Code/Java/File-Input-Output/TheuseofDataOutputStreamandDataInputStream.htm and this http://download.oracle.com/javase/1.4.2/docs/api/java/io/OutputStream.html
Upvotes: 0
Reputation: 1108782
You're treating a binary file as text file by using Reader
/Writer
instead of InputStream
/OutputStream
. The BufferedReader#readLine()
eats CRLF bytes.
Just write InputStream
to OutputStream
directly without massaging the bytes to characters and back and removing CRLF bytes. You also don't need to worry about character encoding anymore.
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();
Upvotes: 6