What is the most efficient way on Android to call HTTP Web API calls that return a JSON response?

前端 未结 2 581
逝去的感伤
逝去的感伤 2020-12-22 18:00

I\'m the perfectionist type, I already got web API calls working fine with Google Places API (just as an example), but I feel it\'s sometimes slow or maybe I\'m not doing it

2条回答
  •  死守一世寂寞
    2020-12-22 19:02

    ------Create a Service Handler Class to your Project--------

    public class ServiceHandler {
    
    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;
    
    public ServiceHandler() {
    }
    
    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }
    
    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
            List params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
    
            // Checking http request method type
            if (method == POST) {
                Log.e("in POST","in POST");
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    Log.e("in POST params","in POST params");
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }
                Log.e("url in post service",url);
                httpResponse = httpClient.execute(httpPost);
    
            } else if (method == GET) {
                // appending params to url
                Log.e("in GET","in GET");
                if (params != null) {
                    Log.e("in GET params","in GET params");
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                Log.e("url in get service",url);
                HttpGet httpGet = new HttpGet(url);
    
                httpResponse = httpClient.execute(httpGet);
    
            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    
        return response;
    
    }
    public String makeServiceCallIMAGE(String url, int method,
            List params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;
    
            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
    
                }
    
                httpResponse = httpClient.execute(httpPost);
    
            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);
    
                httpResponse = httpClient.execute(httpGet);
    
            }
            httpEntity = httpResponse.getEntity();
            response = EntityUtils.toString(httpEntity);
    
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }
    }
    

    --------------AsyncTask For Login------------------

    public class Login_Activity extends ActionBarActivity {
    
    //Internet Service
    NetworkConnection nw;
    ProgressDialog prgDialog;
    Boolean netConnection = false;
    //
    
    //Login API
    String loginURL ="url";
    //
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
    
        nw = new NetworkConnection(getApplicationContext());
        prgDialog = new ProgressDialog(this);
        // Set Cancelable as False
        prgDialog.setCancelable(false);
    
        new LoginOperation().execute();
    }
    
    private class LoginOperation  extends AsyncTask {
    
        String status, message;
        @Override
        protected void onPreExecute() {
            // Set Progress Dialog Text
            prgDialog.setMessage("Logging...");
            prgDialog.show();
        }
    
        @Override
        protected Void doInBackground(String... urls) {
    
            if(nw.isConnectingToInternet() == true)
            {
                try
                {
                    List nameValuePairs = new ArrayList();
                    nameValuePairs.add(new BasicNameValuePair("method", "ClientesLogin"));
                    nameValuePairs.add(new BasicNameValuePair("Email", str_Email));
                    nameValuePairs.add(new BasicNameValuePair("Senha", str_Password));
                    ServiceHandler sh  = new ServiceHandler();
                    String response = sh.makeServiceCall(loginURL, ServiceHandler.GET,
                            nameValuePairs);
    
                    Log.e("response", response);
    
                    JSONObject js = new JSONObject(response);
                    status = js.getString("status");
                    Log.e("status",status);
    
                    if(status.contains("Fail"))
                    {
                        message = js.getString("message");
                    }
                    /*else
                    {
                        JSONObject jslogin=js.getJSONObject("user_list");
                        for (int i = 0; i < jslogin.length(); i++) {
                        }
                    }*/
    
                }catch(Exception ex){
    
                }
                netConnection = true;
            }else
            {
                netConnection = false;
            }
    
            return null;
        }
    
        @Override
        protected void onPostExecute(Void result) {
            prgDialog.dismiss();
    
            if(netConnection == false)
            {
                Toast toast = Toast.makeText(getApplicationContext(),"Internet is not available. Please turn on and try again.", Toast.LENGTH_LONG);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
            }
            else
            {
                if(status.contains("Success"))
                {
                    Toast toast = Toast.makeText(getApplicationContext(), "Login Successful", Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
    
                    Intent i=new Intent(Login_Activity.this,home_page_activity.class);
                    startActivity(i);
                }
                else{
                    Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                }
            }
            super.onPostExecute(result);
        }
    }
    }
    

    ---------------Network Connection class---------------------

    public class NetworkConnection {
    
    Context context;
    
    public NetworkConnection(Context context){
        this.context = context;
    }
    
    public boolean isConnectingToInternet(){
        ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
          if (connectivity != null) 
          {
              NetworkInfo[] info = connectivity.getAllNetworkInfo();
              if (info != null) 
                  for (int i = 0; i < info.length; i++) 
                      if (info[i].getState() == NetworkInfo.State.CONNECTED)
                      {
                          return true;
                      }
          }
          return false;
    }
    }
    

    JSONArray main1 = js.getJSONArray("Test 1");
    
      for (int i = 0; i < main1.length(); i++) {
    
        JSONObject jsonObject = main1.getJSONObject(i);
    

提交回复
热议问题