I've got two methods in a class:
private static InputStream getSongStream(String ip, String id){
try {
URL url = new URL("http://"+ ip + "/" + Client.streamphp);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data); //Data is a simple Http Post that is know to work
wr.flush();
wr.close();
return conn.getInputStream();
} catch (MalformedURLException badurl) {
System.out.println(badurl);
return null;
} catch (IOException noconnection) {
System.out.println(noconnection);
return null;
}
}
public static void downloadSong(String ip, String id, String path){
InputStream rd = Client.getSongStream(ip, id);
try {
OutputStream stream = new FileOutputStream(new File(path));
byte[] buffer = new byte[4096];
int len;
while ((len = rd.read(buffer)) > 0) { //Here I get NullPointerException
stream.write(buffer, 0, len);
}
stream.close();
rd.close();
} catch (IOException noconnection) {
System.out.println(noconnection);
}
}
The line commented in the second method is the problem, if I put all in the same method I can download the song without problems, but not if I separate them.
Any ideas? I would like to have them separated to reuse getSongStream.