Strange problems with the Spring RestTemplate in Android application

android, java, post, rest, spring

Solution

I think you are targeting your app Android 4.0-4.2. Then you must perform all your operations in the background, not main (UI) thread. You are performing an authorization process, as I see. It's a short operation, so it's better for you to use `AsyncTask` for this. Here is howto for this on androidDevelopers:

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

You should override doInBackground(Params...) in such a 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;
    }
}

And then call it in your BeginAuthorization(View view):

new LoginTask().execute(URL);

P.S. Also if you write Java please use correct naming conventions. Instead of this `_response` please write `response`.

Problem

I began to use RESTful api of the Spring Framework in my android client application. But I have encountered with problems when I tried to execute HTTP request via postForObject/postForEntity methods. 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 what am I doing wrong? How to fix this? May there is other way to do it? I really need a help. Thanks in advance!

Original source