Android services with RestFull web services

旧巷老猫 提交于 2019-12-07 18:53:05

问题


I am new in android. I need to call RestFull web services from my app. Can i call RestFull web services from android service? if yes then how it implement?


回答1:


Consuming Webservices directly via HTTP method in android causes ANR (Android not responding) exception and Network On Main Thread exception. Hence you would have to use an ASYNCTASK to call /consume web-services.

Permission Required:

<uses-permission android:name="android.permission.INTERNET" />

Code snippet:

This is the main activity in the android client. From here, the web-service would be consumed on some particular trigger, say user clicks a button. Use an AsyncTask for calling the web-service in background

class MainActivity extends Activity
{
    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        // Event that triggers the webservice call
        new AsyncTaskOperation().execute();
    }
/* Async Task called to avoid Android Network On Main Thread Exception. Web services need to be consumed only in background.     */
    private class AsyncTaskOperation extends AsyncTask <String, Void, Void>
    {

        private JSONObject json = null;
        private ProgressDialog Dialog = new ProgressDialog(MenuActivity.this);
        private boolean errorFlag = false;

        protected void onPreExecute() {

            Dialog.setMessage("Calling WebService. Please wait.. ");
            Dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            Dialog.setInverseBackgroundForced(false);
            Dialog.setCancelable(false);
            Dialog.show();
        }       

        @Override
        protected Void doInBackground(String... paramsObj) 
        {
            // Calling webservice to check if location reached.
            json = RestClientServicesObject.callWebService(params);

            if (json == null)
            {
                // Network error/Server error. No response from web-service.
                errorFlag = true;
            }
            else
            {
                try 
                {
                    // Do action with server response
                } catch (JSONException e) 
                {
                    e.printStackTrace();
                }       
            } // End of if response obtained from web-service.
            return null;
        }


        protected void onPostExecute(Void unused) 
        {
            Dialog.dismiss();

            if (errorFlag)
            {
                // No response from server
                new AlertDialogDisplay().showAlertInfo (MainActivity.this, "Server Error", "Network / Server Error. Please try after sometime.");
            }
            else
            {
                // Perform activities based on server response
            }// End of if response obtained from server
        }// End of method onPostExecute

    } // End of class AsyncTask


}// End of class Main Activity.

This is the HTTPClient code for WebServices Consuming (POST REQUEST)

public class RestClientServices {



    /* Call Web Service and Get Response */
    private HttpResponse getWebServiceResponse(String URL, ArrayList <NameValuePair> params)
    {
        HttpResponse httpResponse = null;
        try 
        {
            HttpParams httpParameters = new BasicHttpParams();

            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpPost httpPost = new HttpPost(URL);
            try 
            {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            } catch (UnsupportedEncodingException e) {
            }
            httpResponse = httpClient.execute(httpPost);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }       
        return httpResponse;
    }
    /* Get the Web Service response as a JSON Object */
    private JSONObject responseToJSON (HttpResponse httpResponse)
    {
        InputStream is = null;
        String json = "";
        JSONObject jObj = null;
        HttpEntity httpEntity  = null;
        try
        {
            if (httpResponse != null)
            {
                httpEntity = httpResponse.getEntity();
                try {
                    is = httpEntity.getContent();

                } catch (IllegalStateException e1) {
                    Log.v("a", "Error while calling web services " +e1);
                    e1.printStackTrace();
                } catch (IOException e1) {
                    Log.v("a", "Error while calling web services " +e1);
                    e1.printStackTrace();
                }           
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    reader.close();
                    // Closing the input stream will trigger connection release
                    is.close();
                    json = sb.toString();
                } catch (Exception e) {
                    Log.e("a", "Buffer Error. Error converting result " + e.toString());
                }

                // try parse the string to a JSON object
                try {
                    jObj = new JSONObject(json);
                    Log.v("a", "JSON Object is  " +jObj);
                } catch (JSONException e) {
                    Log.e("JSON Parser", "Error parsing data " + e.toString());
                }

            }
        }
        catch (Exception e)
        {
            Log.e("a", "Error while calling web services " +e);
        }
        finally
        {
            // Release the response
            try {

                if (httpEntity != null)
                {
                    httpEntity.consumeContent();
                }
                //httpResponse.getEntity().getContent().close();
            } catch (IllegalStateException e) {
                Log.e("a", "Error while calling web services " +e);
                e.printStackTrace();
            } catch (IOException e) {
                Log.e("a", "Error while calling web services " +e);
                e.printStackTrace();
            }       
        }


        // return JSON Object
        return jObj;
    }

    /* Call the web service and get JSON Object response */
    public JSONObject getResponseAsJSON (String URL, ArrayList <NameValuePair> params)
    {
        return responseToJSON(getWebServiceResponse(URL,params));
    }

}



回答2:


Android App are single thread applications, which means an app will run on single one and only thread, if you try to call HTTP operations from that thread it will give you the exception. To do network operations like calling Restfull web services or some other network operation you need to create a class which extends AsyncTask.

Here is the sample code.

public class AsyncInvokeURLTask extends AsyncTask<Void, Void, String> {
    private final String                 mNoteItWebUrl = "your-url.com";
    private ArrayList<NameValuePair>     mParams;
    private OnPostExecuteListener        mPostExecuteListener = null;

    public static interface OnPostExecuteListener{
        void onPostExecute(String result);
    }

    AsyncInvokeURLTask(
        ArrayList<NameValuePair> nameValuePairs,
        OnPostExecuteListener postExecuteListener) throws Exception {

        mParams = nameValuePairs;
        mPostExecuteListener = postExecuteListener;
        if (mPostExecuteListener == null)
            throw new Exception("Param cannot be null.");
    }

    @Override
    protected String doInBackground(Void... params) {

        String result = "";

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(mNoteItWebUrl);

        try {
            // Add parameters
            httppost.setEntity(new UrlEncodedFormEntity(mParams));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            if (entity != null){
                InputStream inStream = entity.getContent();
                result = convertStreamToString(inStream);
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        if (mPostExecuteListener != null){
            try {
                JSONObject json = new JSONObject(result);
                mPostExecuteListener.onPostExecute(json);
            } catch (JSONException e){
                e.printStackTrace();
            }
        }
    }

    private static String convertStreamToString(InputStream is){
        BufferedReader reader = new BufferedReader(
            new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

You can read more about AsyncTask here on Android Official Site.

P.S. Code is taken from here.



来源:https://stackoverflow.com/questions/24199494/android-services-with-restfull-web-services

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!