How to call a RESTful Method from Android?

后端 未结 1 741
南旧
南旧 2021-01-28 22:40

I\'ve tried two different ways to call a simple REST method from Android; said REST method - which works from other clients - simply returns an int val such as 17.

Both

相关标签:
1条回答
  • 2021-01-28 23:08

    I've got it working now. There's an article about it here.

    This is the code from there without any explanation:

    public class MainActivity extends ActionBarActivity {
    
        private GetDepartmentsCount _getDeptsCount;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            Button getDeptsCountBtn = (Button)findViewById(R.id.DeptsCountBtn);
            getDeptsCountBtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    _getDeptsCount = new GetDepartmentsCount();
                    _getDeptsCount.execute("http://10.0.2.2:28642/api/Departments/GetCount?serialNum=4242");
                }
            });
        }
    
        @Override
        public void onStop() {
            super.onStop();
            _getDeptsCount.cancel(true);
        }
    
        private class GetDepartmentsCount extends AsyncTask<String, String, String> {
    
            @Override
            protected String doInBackground(String... params) {
    
                String urlString = params[0]; // URL to call
                String result = "";
    
                // HTTP Get
                try {
                    URL url = new URL(urlString);
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    if (null != inputStream)
                        result = IOUtils.toString(inputStream);
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                    return e.getMessage();
                }
                return result;
            }
    
            @Override
            protected void onPostExecute(String result) {
                EditText dynCount = (EditText)findViewById(R.id.dynamicCountEdit);
                dynCount.setText(result + " records were found");
                Log.i("FromOnPostExecute", result);
            }
        } 
    
    }
    
    0 讨论(0)
提交回复
热议问题