I have written a REST web service in Netbean IDE using Jersey Framework and Java.
For every request the user needs to provide a username and a password, I know that this authentication is not a best practice (using a curl command like: curl -u username:password -X PUT http://localhsot:8080/user
).
Now I want to call a REST web service from an Android Class.
How should I do it?
I have an Android Class which uses DefaultHttpClient
and CredentialUsernameAndPassword
, but when I run it in Eclipse, sometimes I get a runtime exception or SDK exception.
Recently discovered that a third party library - Square Retrofit can do the job very well.
Defining REST endpoint
Getting the concrete service
Calling the REST endpoint
The library handles the json serialization and deserailization for you. You may customize the serialization and deserialization too.
Using Spring for Android with RestTemplate https://spring.io/guides/gs/consuming-rest-android/
I use this REST Client for my android. This looks really cool. Nice work by Luke.
http://lukencode.com/2010/04/27/calling-web-services-in-android-using-httpclient/
Stop with whatever you were doing ! :)
Implement the RESTful client as a SERVICE and delegate the intensive network stuff to activity independent component: a SERVICE.
Watch this insightful video http://www.youtube.com/watch?v=xHXn3Kg2IQE where Virgil Dobjanschi is explaining his approach(es) to this challenge...
This is an sample restclient class
There are tons of libraries available for doing this
Retrofit replaces the traditional AsyncTask and it has its own background task so you really don't have to worry about it. The performance is also very good relative to AsyncTask.
Check it here,
http://square.github.io/retrofit/
A complete example of Retrofit could be found here,
https://futurestud.io/blog/retrofit-getting-started-and-android-client/
Volley is also efficient and easy to use. You can take a look here:
https://github.com/mcxiaoke/android-volley
There a bunch of resources on the web on how to use it:
http://www.androidhive.info/2014/05/android-working-with-volley-library-1
AsyncTask
OR You should use implement an
AsyncTask
and then override the methoddoInTheBackground()
- where you can implement the REST call.Then you can use
onPostExecute()
to let the UI thread process the results that were returned in the previous step.This answer provides a good example of how to implement
AsyncTask
. see AsyncTask Android examplePer Ruffles's comment below, here's a more relevant example of REST call using AsyncTask: http://alvinalexander.com/android/android-asynctask-http-client-rest-example-tutorial