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!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With