Thursday, 22 May 2014

Download zip file using HTTPPOST in Android :

Step 1 :
Create an Asybktask
new save().execute();
Step 2:
In Asynktask
public class save extends AsyncTask<String, Integer, byte[]> {
 @Override
 protected void onPostExecute(byte[] result) {
 super.onPostExecute(result);
}
byte[] data;
@Override
protected byte[] doInBackground(String... arg0) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
 MultipartEntity entity = new MultipartEntity();

//Add required post data 
entity.addPart("id", new StringBody("1"));
 entity.addPart("api_key", new StringBody("key"));
 entity.addPart("api_password", new StringBody("password"));

//Execute post method
 httppost.setEntity(entity);

//Read the response
 HttpResponse response = httpclient.execute(httppost);
 InputStream input = response.getEntity().getContent();
 data = new byte[input.available()];
 input.read(data);
 File path = new File(Environment.getExternalStorageDirectory()+"/asdfg.zip");
 if (!path.isFile()){
 path.createNewFile();
 }
 OutputStream outputStream = 
 new FileOutputStream(path);
 
 int read = 0;
 byte[] bytes = new byte[1024];
 
 while ((read = input.read(bytes)) != -1) {
 outputStream.write(bytes, 0, read);
 }
 } catch (ClientProtocolException e) {
 } catch (IOException e) {
 }
 return data;
 }
}

No comments:

Post a Comment