Thursday, November 3, 2011

Sending multipar request to server in Android (like image and data)

/**
     * here list of user accounts and 6 phone numbers,6 emailids,and Service provicers information are sending .
     * This method creates Account at server and returns acknowledge
     * of creation of successful account.
     * @throws JSONException
     */

    public String getcreatedAccount(final String lid2, final String pwd2,final String uname,
            final String city2,final String country2,
            ArrayList<Phnos> mPhnolist,ArrayList<EmailIds> mEmailidlist,final String issp,final String refid,final String mcity,final String mcnt,final String pdes,ArrayList<Service1> serviceList,final String mid,final String memailid,final String mstreet,final String mpost,final String selectcat,String imgData) throws JSONException {
        Log.e("mcity",""+mcity);
        Log.e("pdes",""+pdes);
        String mRes=null;
        //mDBHelper =mAppMgr.getDbHelper();

        //mRes = mDBHelper.createAccountfun(account) ;
        ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("client", "mc"));
        postParameters.add(new BasicNameValuePair("loginId", lid2));
        postParameters.add(new BasicNameValuePair("password", pwd2));
        postParameters.add(new BasicNameValuePair("profileName",uname));
        if(mPhnolist.size()!=0){
           
            //String json=jsonRequestConstructor(mPhnolist);
            //postParameters.add(new BasicNameValuePair("phlist",json));
           

        }
        if(mEmailidlist.size()!=0){
        //String json2=jsonRequestConstructorForemailid(mEmailidlist);
        //postParameters.add(new BasicNameValuePair("emaillist",json2));

    }
        postParameters.add(new BasicNameValuePair("city",city2));
        postParameters.add(new BasicNameValuePair("country",country2));
        postParameters.add(new BasicNameValuePair("mailid_primary",mEmailidlist.get(0).emailid));
        if(mEmailidlist.size()>=2){
        postParameters.add(new BasicNameValuePair("mailid_other1",mEmailidlist.get(1).emailid));
        }
        if(mEmailidlist.size()>=3){
        postParameters.add(new BasicNameValuePair("mailid_other2",mEmailidlist.get(2).emailid));
        }
        if(mEmailidlist.size()>=4){
        postParameters.add(new BasicNameValuePair("mailid_other3",mEmailidlist.get(3).emailid));
        }
        if(mEmailidlist.size()>=5){
        postParameters.add(new BasicNameValuePair("mailid_other4",mEmailidlist.get(4).emailid));
        }
        if(mEmailidlist.size()>=6){
        postParameters.add(new BasicNameValuePair("mailid_other5",mEmailidlist.get(5).emailid));
        }
       
        postParameters.add(new BasicNameValuePair("type_primary",mPhnolist.get(0).phno));
       
        if(mPhnolist.size()>=2){
        postParameters.add(new BasicNameValuePair("type_other1",mPhnolist.get(1).phno));
        }
        if(mPhnolist.size()>=3){
        postParameters.add(new BasicNameValuePair("type_other2",mPhnolist.get(2).phno));
        }
        if(mPhnolist.size()>=4){
        postParameters.add(new BasicNameValuePair("type_other3",mPhnolist.get(3).phno));
        }
        if(mPhnolist.size()>=5){
        postParameters.add(new BasicNameValuePair("type_other4",mPhnolist.get(4).phno));
        }
        if(mPhnolist.size()>=6){
        postParameters.add(new BasicNameValuePair("type_other5",mPhnolist.get(5).phno));
        }
        postParameters.add(new BasicNameValuePair("reference_id",refid));
        postParameters.add(new BasicNameValuePair("catalog_version_id",Integer.toString(mCatv)));
        postParameters.add(new BasicNameValuePair("isServiceProvider",issp));
        if(issp.equals("1")){
            postParameters.add(new BasicNameValuePair("spProfileDesc",pdes));
            if(serviceList.size()!=0){
            postParameters.add(new BasicNameValuePair("service_name",serviceList.get(0).service_name));
            Log.e("serviceList.get(0).service_name",""+serviceList.get(0).service_name);
            postParameters.add(new BasicNameValuePair("service_desc",serviceList.get(0).service_des));
            Log.e("serviceList.get(0).service_des",""+serviceList.get(0).service_des);
           
            postParameters.add(new BasicNameValuePair("service_duration",serviceList.get(0).timeslot));//mcharge
            Log.e("serviceList.get(0).timeslot",""+serviceList.get(0).timeslot);
            postParameters.add(new BasicNameValuePair("service_charge",serviceList.get(0).service_charge));
            Log.e("serviceList.get(0).service_charge",""+serviceList.get(0).service_charge);
            }
            postParameters.add(new BasicNameValuePair("merchant_acc_id",mid));
            Log.e("merchant_acc_id",mid);
            postParameters.add(new BasicNameValuePair("merchant_city",mcity));
            Log.e("merchant_city",mcity);
            postParameters.add(new BasicNameValuePair("merchant_emai_id",memailid));
            Log.e("merchant_emai_id",memailid);
            postParameters.add(new BasicNameValuePair("merchant_country",mcnt));
           
            Log.e("merchant_country",""+mcnt);
            postParameters.add(new BasicNameValuePair("merchant_street_add",mstreet));//mcharge
            Log.e("mstreet",""+mstreet);
            postParameters.add(new BasicNameValuePair("merchant_postal_code",mpost));
        Log.e("merchant_postal_code",mpost);
        postParameters.add(new BasicNameValuePair("select_category",selectcat));
            Log.e("selectcat",""+selectcat);
           

        }   


        String response = null;
        try {
            response = CustomHttpClient.executeHttpPost1(SM_SERVER_URL_PREFIX+"register", postParameters);
            String res=response.toString();
            mRes= res.replaceAll("\\s+","");
            res1=new RegistrationRes();
            res1=JSONSMParser.parseRegisrationstatus( mRes);
            Log.e("res1.status_code",""+res1.status_code);
            Log.e("login res",""+mRes);

        }
        catch (Exception e) {
            Log.e("exception",e.toString());
        }
       

        return res1.status_code;


    }


//following is supporting class for executeHttp request and response

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;

import java.net.HttpURLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ByteArrayBody;
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.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;


import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.util.Log;

public class CustomHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;
    private static Bitmap bitmap;
    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
           
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
          
            HttpPost request = new HttpPost(url);
          
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            Log.e( "postParameters",""+ postParameters);
            Log.e("formEntity",""+formEntity);

            /*    MultipartEntity entity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);

            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bitmap.compress(CompressFormat.JPEG, 100, bos);
            byte[] data = bos.toByteArray();
            entity.addPart("returnformat", new StringBody("json"));
            entity.addPart("uploaded", new ByteArrayBody(data,
                    "myImage.jpg"));*/
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
//this bewlow code to send image and data with multipart request
    public static String executeHttpPost1(String url,ArrayList<NameValuePair> postParameters ) throws Exception {
        HttpPost post = new HttpPost(url);
     Bitmap bitmap; 
        String Result_STR=null;
        HttpClient client = new DefaultHttpClient();
        HttpEntity resmarkMessagesReadFrom =null;
        MultipartEntity reqmarkMessagesReadFrom = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        try {
            Log.e("postParameters.size()",""+postParameters.size());
            for(int i=0;i<postParameters.size();i++){
                Log.e("parameters",""+postParameters.get(i).getName()+""+postParameters.get(i).getValue());
            reqmarkMessagesReadFrom.addPart(postParameters.get(i).getName(), new StringBody(postParameters.get(i).getValue()));
            if(postParameters.get(i).getName().equals("imgpath")){
                  bitmap = BitmapFactory.decodeFile(postParameters.get(i).getValue()); 
             
                     // you can change the format of you image compressed for what do you want; 
                    //now it is set up to 640 x 480; 
             
                       Bitmap bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true); 
                       ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
                 
                  // CompressFormat set up to JPG, you can change to PNG or whatever you want; 
             
                    bmpCompressed.compress(CompressFormat.JPEG, 100, bos); 
                        byte[] data = bos.toByteArray();
                        reqmarkMessagesReadFrom.addPart("myImage", new ByteArrayBody(data, "temp.jpg")); 
                         
                               
            }
            post.setEntity(reqmarkMessagesReadFrom);
           
            }
             HttpResponse response = client.execute(post);
              resmarkMessagesReadFrom = response.getEntity();
            if (resmarkMessagesReadFrom != null) {
                Result_STR=EntityUtils.toString(resmarkMessagesReadFrom);
               // mMSGBox.setText(Result_STR);
            }
        }
        finally {
           
            }
       
return Result_STR;
    }
   
    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

No comments:

Post a Comment