Vihaan Verma
Vihaan Verma

Reputation: 13143

android httpclient to trigger a download from server

I have created a HTTP file server with the objective of transferring media files (mp3, ogg etc) to an Android device. When the server is accessed from the android browser like

10.0.2.2:portNumber/path/to/file

The server initiates the file download process. Of course the customer would not do such a thing, Its fine for testing the file server. I m new to Android development and have learned that httpclient package can manage get/post requests. Here is the sample code I have been using for reading the response

DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
  HttpResponse execute = client.execute(httpGet);
  InputStream content = execute.getEntity().getContent();

  BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
  String s = "";
  while ((s = buffer.readLine()) != null) {
    response += s;
  }
} catch (Exception e) {
  e.printStackTrace();
}

return response;

The above code works fine when the server sends a list of file in JSON. Since the server part of sending file has been coded, the point where I m stuck is in retrieving the media file on android.

I m confused about how to receive the mp3 files send by the server. Should they be read in a stream ? Thanks

Upvotes: 2

Views: 3718

Answers (1)

D Yao.
D Yao.

Reputation: 401

Yes, you want to read the file onto disk via an inputstream. Here's an example. If you don't want a file download progress bar then remove the progress related code.

try {
        File f = new File("yourfilename.mp3");
        if (f.exists()) {
            publishProgress(100,100);
        } else {
            int count;
            URL url = new URL("http://site:port/your/mp3file/here.mp3");
            URLConnection connection = url.openConnection();
            connection.connect();
            int lengthOfFile = connection.getContentLength();
            long total = 0;
            InputStream input = new BufferedInputStream(url.openStream());
            OutputStream output = new FileOutputStream(f);
            byte data[] = new byte[1024];
            while ((count = input.read(data)) != -1) {
                total += count;
                publishProgress((int)(total/1024),lengthOfFile/1024);
                output.write(data, 0, count);
            }
            output.flush();
            output.close();
            input.close();
        }
    } catch (Exception e) {
        Log.e("Download Error: ", e.toString());
    }

Upvotes: 2

Related Questions