Java – Strange problem with Spring RestTemplate in Android applications

Strange problem with Spring RestTemplate in Android applications… here is a solution to the problem.

Strange problem with Spring RestTemplate in Android applications

I started using the Spring Framework’s RESTful APIs in my android client applications. But I ran into problems when I tried to perform an HTTP request through the postForObject/postForEntity method. Here is my code:

public String _URL = "https://someservice/mobile/login";
public void  BeginAuthorization(View view)
{     
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
         HttpEntity<String> _entity = new HttpEntity<String>(requestHeaders);
        RestTemplate templ = new RestTemplate();
        templ.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        templ.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
        ResponseEntity<String> _response = templ.postForEntity(_URL,_entity,String.class); //HERE APP CRASHES
        String _body = _response.getBody();

So the question is what am I doing wrong? How to solve this problem? Is there another way?

I really need help. Thanks in advance!

Solution

I think your app target is Android 4.0-4.2. Then you must do everything in the background, not the main (UI) thread. As I can see, you are going through the authorization process. This is a short operation, so you’d better use AsyncTaskit for this . Here’s how to do it on androidDevelopers:

http://developer.android.com/reference/android/os/AsyncTask.html

You should override doInBackground(Params…) in this way:

class LoginTask extends AsyncTask<String,Void,Void>
{
    @Override
    protected Void doInBackground(String... params) {
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON); 
        HttpEntity<String> _entity = new HttpEntity<String>(requestHeaders);
        RestTemplate templ = new RestTemplate();
        templ.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        templ.getMessageConverters().add(new MappingJacksonHttpMessageConverter());
        ResponseEntity<String> _response = templ.postForEntity(params[0],_entity,null) //null here in order there wasn't http converter errors because response type String and [text/html] for JSON are not compatible;
        String _body =  _response.getBody();
        return null;
    }
}

Then call it in your BeginAuthorization(View view):

new LoginTask().execute(URL);

P.S. Also, if you write Java, use the correct naming convention. Instead of this _response please write response.

Related Problems and Solutions