使用RestFul Web服务的Android服务

时间:2014-06-13 07:02:46

标签: android web-services webservice-client

我是android新手。我需要从我的应用程序调用RestFul Web服务。 我可以从Android服务调用RestFul Web服务吗?如果是,那么它如何实施?

2 个答案:

答案 0 :(得分:1)

直接通过Android中的HTTP方法使用Webservices导致ANR(Android无响应)异常和Network On Main Thread异常。因此,您必须使用ASYNCTASK来调用/使用Web服务。

需要许可:

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

代码段:

这是android客户端的主要活动。从这里开始,Web服务将在某个特定触发器上消耗,比如用户单击按钮。 使用AsyncTask在后台调用Web服务

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.

这是Web服务消费的HTTPClient代码(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));
    }

}

答案 1 :(得分:1)

Android应用程序是单线程应用程序,这意味着应用程序将在单个线程上运行,如果您尝试从该线程调用HTTP操作,它将为您提供异常。要进行网络操作,如调用Restfull Web服务或其他一些网络操作,您需要创建一个扩展AsyncTask的类。

以下是示例代码。

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();
    }
}

您可以在Android官方网站上阅读有关AsyncTask here的更多信息。

P.S。代码取自here