Monday, December 22, 2014

WebAPIRequest.cs

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class WebAPIRequest
{
    public static String convertStreamToString(InputStream is)
            throws IOException {
        if (is != null)
        {
            StringBuilder sb = new StringBuilder();
            String line;
            try {
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is, "UTF-8"));
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append("\n");
                }
            } finally {
                is.close();
            }
            return sb.toString();
        } else {
            return "";
        }
    }

    public Document performPost(String url, String body) {
        Document doc = null;

        try {

            HttpParams basicparams = new BasicHttpParams();
            URI uri = new URI(url);
            HttpPost method = new HttpPost(uri);
            int timeoutConnection = 60000;
            HttpConnectionParams.setConnectionTimeout(basicparams,timeoutConnection);
            DefaultHttpClient client = new DefaultHttpClient(basicparams);
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            body = body.replaceAll("%20", " ");
            String[] parameters = body.split("&");
            for (int i = 0; i < parameters.length; i++) {
                String[] parameter = parameters[i].split("=");
                if (parameter.length >= 2) {
                    nameValuePairs.add(new BasicNameValuePair(parameter[0],
                            parameter[1]));
                }
            }
            method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse res = client.execute(method);

            InputStream data = res.getEntity().getContent();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            DocumentBuilder db = dbf.newDocumentBuilder();
            doc = db.parse(data);
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return doc;
    }

    public String performPostAsString(String url,
            ArrayList<NameValuePair> nameValuePairs) {
        String value = null;

        try {

            HttpParams basicparams = new BasicHttpParams();
            URI uri = new URI(url);
            HttpPost method = new HttpPost(uri);
            int timeoutConnection = 60000;

            HttpConnectionParams.setConnectionTimeout(basicparams,
                    timeoutConnection);
            DefaultHttpClient client = new DefaultHttpClient(basicparams);

            method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            HttpResponse res = client.execute(method);

            InputStream data = res.getEntity().getContent();
            value = convertStreamToString(data);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return value;
    }

    public String performGet(String url) {

        url = url.replace(" ", "%20");

        System.out.println(url);

        String strres = null;
        try {
            HttpParams basicparams = new BasicHttpParams();
            int timeoutConnection = 60000;
            HttpConnectionParams.setConnectionTimeout(basicparams,
                    timeoutConnection);
            DefaultHttpClient client = new DefaultHttpClient(basicparams);
            URI uri = new URI(url);
            // url.replaceAll("%20"," ");
            HttpGet method = new HttpGet(uri);
            HttpResponse res = client.execute(method);
            InputStream data = res.getEntity().getContent();
            strres = convertStreamToString(data);

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return strres;
    }
}


How to use in webservices

 

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.Cust.HttpServicepk.WebAPIRequest;

import android.R.string;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainAtivity extends Activity {
    ListView lv;
   
    String respo = "";
    Button btnback;
   
   
    WebAPIRequest wb = new WebAPIRequest();
    ArrayList<String> CatList = new ArrayList<String>();
    ArrayList<String> CatIDList = new ArrayList<String>();
    DBHelper db = new DBHelper(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnback = (Button) findViewById(R.id.buttonback);
        btnback.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent i = new Intent(getApplicationContext(), Homescr.class);
                startActivity(i);
            }
        });
      
        try
        {
            db.createDataBase();
          
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String url = "http://www.roms.webege.com/service_category.php";

        new display_activity().execute(url);

        lv = (ListView) findViewById(R.id.listView1);

OnItemClickListener clickListener = new OnItemClickListener()
{

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
              
                // String CatID = CatIDList.toArray()[arg2].toString();
                String CatID = CatIDList.get(arg2);
                String Catname = CatList.get(arg2);
                Intent i = new Intent(getApplicationContext(), Item.class);
                i.putExtra("ID", CatID);
                i.putExtra("CatName", Catname);

                startActivity(i);

                Toast.makeText(getApplicationContext(), CatID, 0).show();
            }

        };
        lv.setOnItemClickListener(clickListener);

    }

    public class custlist extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return CatList.toArray().length;
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return CatList.toArray()[arg0];
        }

        @Override
        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            // TODO Auto-generated method stub
            LayoutInflater layoutInflater;
            layoutInflater = getLayoutInflater();
            layoutInflater = LayoutInflater.from(MainAtivity.this);
            arg1 = layoutInflater.inflate(R.layout.raw, null);
            TextView tv = (TextView) arg1.findViewById(R.id.textViewstarter);
            TextView tvid = (TextView) arg1.findViewById(R.id.catid);
            // Log.i("NAME",CatList.toArray()[arg0].toString());
            tv.setText(CatList.toArray()[arg0].toString());
            tvid.setText(CatIDList.toArray()[arg0].toString());
            return arg1;

        }

    }

    public class display_activity extends AsyncTask<String, Void, Void>
    {

        ProgressDialog pd;

        @Override
        protected void onPreExecute()
        {
            // TODO Auto-generated method stub
            super.onPreExecute();
            Log.i("CALL", "CALL");

            pd = ProgressDialog.show(MainAtivity.this, "Loading .....",
                    "Fatching data");

        }

        @Override
        protected Void doInBackground(String... arg0) {
            // TODO Auto-generated method stub
            try {
                respo = wb.performGet(arg0[0]);
                Log.i("JSON", respo);
                Toast.makeText(getApplicationContext(), respo, 0).show();
            } catch (Exception e) {
                // TODO: handle exception

                Log.i("ERROR", e.getMessage().toString());

            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            Log.i("CALL", "CALL");
          
          
            JSONObject jsonResponse;
            JSONArray jsarray;
          
            // JSONArray CatID;
            try {
                String[] resspdata = respo.toString().trim().split("<!");
                Log.i("SPData", resspdata[0].toString());

                jsonResponse = new JSONObject(respo);
                // Log.i("JSON", jsonResponse.toString());
                jsarray = new JSONArray();
                jsarray = jsonResponse.getJSONArray("members");
                Log.i("JSON", jsarray.getString(1));
                //
              
                //
                for (int i = 0; i < jsarray.length(); i++)
                {
                    JSONObject row = jsarray.getJSONObject(i);
                  
                    String CatName1 = row.getString("CatName");
                    String CatID = row.getString("CatID");
                    CatList.add(CatName1);
                    // Strin = row.getString("name");
                    CatIDList.add(CatID);

                }
                // CatIDList.get(1);
                //

                custlist c = new custlist();
                lv.setAdapter(c);

                // Log.i("AFTJSON", "AFTJSON" + jsonResponse.get("username"));
                // Log.i("AFTJSON", "AFTJSON" + jsonResponse.get("password"));
                // Log.i("AFTJSON", "AFTJSON" + jsonResponse.get("role_id_f"));

            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            try {
                // JSONArray js =new JSONArray(respo);

                // Log.i("JSON", js.getString(1));

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                pd.dismiss();
            }

        }

    }
}