com.nanostuffs.yurdriver.parse.MultiPartRequester.java Source code

Java tutorial

Introduction

Here is the source code for com.nanostuffs.yurdriver.parse.MultiPartRequester.java

Source

package com.nanostuffs.yurdriver.parse;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MIME;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.AsyncTask;

import com.nanostuffs.yurdriver.R;
import com.nanostuffs.yurdriver.utills.AndyConstants;
import com.nanostuffs.yurdriver.utills.AndyUtils;
import com.nanostuffs.yurdriver.utills.AppLog;

/**
 * @author Hardik A Bhalodi
 */
public class MultiPartRequester {

    private Map<String, String> map;
    private AsyncTaskCompleteListener mAsynclistener;
    private int serviceCode;
    private HttpClient httpclient;
    private Activity activity;
    private AsyncHttpRequest request;
    private static final String TAG = "MultiPartRequester";

    public MultiPartRequester(Activity activity, Map<String, String> map, int serviceCode,
            AsyncTaskCompleteListener asyncTaskCompleteListener) {
        this.map = map;
        this.serviceCode = serviceCode;
        this.activity = activity;

        // is Internet Connection Available...

        if (AndyUtils.isNetworkAvailable(activity)) {
            mAsynclistener = (AsyncTaskCompleteListener) asyncTaskCompleteListener;
            request = (AsyncHttpRequest) new AsyncHttpRequest().execute(map.get("url"));
        } else {
            AndyUtils.showToast(activity.getResources().getString(R.string.toast_no_internet), activity);
        }

    }

    class AsyncHttpRequest extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            map.remove("url");
            try {

                HttpPost httppost = new HttpPost(urls[0]);
                httpclient = new DefaultHttpClient();

                HttpConnectionParams.setConnectionTimeout(httpclient.getParams(), 600000);

                MultipartEntity mpEntity = new MultipartEntity();

                for (String key : map.keySet()) {

                    if (key.equalsIgnoreCase("userfile") || key.equalsIgnoreCase("picture")
                            || key.equalsIgnoreCase("userfile") || key.equalsIgnoreCase("vehiclepic")
                            || key.equalsIgnoreCase("vehiclenum") || key.equalsIgnoreCase("licensepic")
                            || key.equalsIgnoreCase("licensepic") || key.equalsIgnoreCase("regpic")) {
                        File f = new File(map.get(key));

                        ContentBody cbFile = new FileBody(f);

                        mpEntity.addPart(key, new FileBody(f));
                    } else {

                        mpEntity.addPart(key, new StringBody(map.get(key), Charset.forName("UTF-8")));

                    }
                    AppLog.Log(TAG, key + "---->" + map.get(key));

                }
                httppost.setEntity(mpEntity);

                ActivityManager manager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);

                if (manager.getMemoryClass() < 25) {
                    System.gc();
                }
                HttpResponse response = httpclient.execute(httppost);

                String responseBody = EntityUtils.toString(response.getEntity(), "UTF-8");

                return responseBody;

            } catch (Exception e) {
                e.printStackTrace();
            } catch (OutOfMemoryError oume) {
                System.gc();
                // Toast.makeText(
                // activity.getParent().getParent(),
                // "Run out of memory please colse the other background apps and try again!",
                // Toast.LENGTH_LONG).show();
            } finally {
                if (httpclient != null)
                    httpclient.getConnectionManager().shutdown();

            }
            return null;

        }

        @Override
        protected void onPostExecute(String response) {

            if (mAsynclistener != null) {
                mAsynclistener.onTaskCompleted(response, serviceCode);
            }

        }
    }

    // private void showToast(String msg) {
    // Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
    // }

    public void cancelTask() {

        request.cancel(true);
        AppLog.Log(TAG, "task is canelled");

    }
}