Wednesday, October 2, 2013

Download binary data

Another common operation is downloading binary data from sever. In this case we want to download an image from the server and show it in our UI.
The operation is very simple because in this case we have to make an HTTP Post request, passing the image name (line 7-10) and read the binary response (line 15-28):
01@Override
02protected byte[] doInBackground(String... params) {
03    String url = params[0];
04    String name = params[1];
05 
06    HttpClient client = new DefaultHttpClient();
07    HttpPost post = new HttpPost(url);
08    List<NameValuePair> paramList = new ArrayList<NameValuePair>();
09    paramList.add(new BasicNameValuePair("name", name));
10    byte[] data = null;
11 
12    try {
13        post.setEntity(new UrlEncodedFormEntity(paramList));
14        HttpResponse resp = client.execute(post);
15        InputStream is = resp.getEntity().getContent();
16        int contentSize = (int) resp.getEntity().getContentLength();
17        System.out.println("Content size ["+contentSize+"]");
18        BufferedInputStream bis = new BufferedInputStream(is, 512);
19 
20        data = new byte[contentSize];
21        int bytesRead = 0;
22        int offset = 0;
23 
24        while (bytesRead != -1 && offset < contentSize) {
25            bytesRead = bis.read(data, offset, contentSize - offset);
26            offset += bytesRead;
27        }
28    }
29    catch(Throwable t) {
30        // Handle error here
31        t.printStackTrace();
32    }
33 
34    return data;
35}
At line 17 we read the response length so that we can create a byte array with the same size (see line 21), then at line 19 we create a buffered input stream to read the response stream. Then we simply read the response filling the data byte array. As result we have:

No comments:

Post a Comment