Skip to content
Hamza Niazi edited this page Jan 24, 2018 · 2 revisions

Implement GET using Spring:

This is an inner class It will execute in the background It is called using HttpRequestTask.execute() method Responsible to GET a single object from provided link Also requires Authentication

private class HttpRequestTask extends AsyncTask<Void, Void, ResponseEntity> { @Override protected ResponseEntity doInBackground(Void... params) { try {` //URL to get the person stored with ID = 1 final String url = "http://192.168.56.1:45455/api/Person/1";

            //RestTemplate is a spring object which is used to communicate with the REST API
            RestTemplate restTemplate = new RestTemplate();

// Resttemplate will resturn a response in jason format, we need to convert it restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());

            //Headers are used to add additional parameters to a link
            //such as API keys, user name and password etc.
            HttpHeaders headers = new HttpHeaders();
            headers.set("APIKey", "1234ABCD5678EFGH");
            
            //Attaching header with link
            HttpEntity<String> entity = new HttpEntity<>(headers);
            
            //Finally executing
            // It will take a URL, a method (GET,POST,PUT,DELETE), an entity(for parameters)
            // and a class for storing received data
            // It will return response which we can then use in onPostExecute method
            ResponseEntity<Person> responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, Person.class);
            return responseEntity;

        } catch (Exception e) {
            Log.e("MainActivity", e.getMessage(), e);
        }

        return null;
    }

    @Override
    protected void onPostExecute(ResponseEntity<Person> personReturned) {
        TextView greetingIdText =  findViewById(R.id.tvID);
        
        // getBody() read the body of the resttemplate object which is returned
        Person person = personReturned.getBody(); 
        
        //Display
        String data = "\nID: " + person.getID()
                    + "\nFirst Name: " + person.getFirstName()
                    + "\nLast Name: " + person.getLastName()
                    + "\nPayRate: " + person.getPayRate()
                    + "\nStart Date: " + person.getStartDate()
                    + "\nEnd Date: " + person.getEndDate();

        greetingIdText.setText(data);
    }

}

`###

Clone this wiki locally