I am working on an asynchronous client server application. After a request is made to a server asynchronously, I should process the message and send back to the client. To receive the response from the server asynchronously, the client should have a sort of RESTful server. Are there any libraries or APIs I can use on android client?
Thanx
Use Retrofit by Square.
(From the site:)
Introduction
Retrofit turns your REST API into a Java interface.
public interface GitHubService {
#GET("/users/{user}/repos")
List<Repo> listRepos(#Path("user") String user);
}
The RestAdapter class generates an implementation of the GitHubService interface.
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("https://api.github.com")
.build();
GitHubService service = restAdapter.create(GitHubService.class);
Each call on the generated GitHubService makes an HTTP request to the remote webserver.
List<Repo> repos = service.listRepos("octocat");
Use annotations to describe the HTTP request:
URL parameter replacement and query parameter support
Object conversion to request body (e.g., JSON, protocol buffers)
Multipart request body and file upload
Also try to avoid AsyncTask, this is a good read on the subject: Robust and readable architecture for an Android App
Actually don't use Asynctask - it's lacks important features needed for a proper network framework (or you just sit and develop them yourself for hours)
Google developed Volley for that in 2013:
Volley automatically schedule all network requests. It means that Volley will be taking care of all the network requests your app executes for fetching response or image from web.
Volley provides transparent disk and memory caching.
Volley provides powerful cancellation request API. It means that you can cancel a single request or you can set blocks or scopes of requests to cancel. Volley provides powerful customization abilities.
Volley provides Debugging and tracing tools
(from: Android – Volley Library Example)
Resources
Google IO 13 presentation
Official Google Repo
Github mirror
Gradle Dependency
compile 'com.mcxiaoke.volley:library:1.0.+'
You can use AsyncTask for the same,
here is official documentation http://developer.android.com/reference/android/os/AsyncTask.html
I am also giving you an example of Asyntask.
class TestAsyncTask extends AsyncTask<Void, Integer, String>
{
protected void onPreExecute (){
Log.d("ASYNCTASK","On pre Exceute......");
}
protected String doInBackground(Void...arg0) {
Log.d("ASYNCTASK","In On doInBackground...");
// make request RESTful service here.
for(int i=0; i<10; i++){
Integer in = new Integer(i);
publishProgress(i); // Update your Ui
}
return "You are in PostExecute";
}
protected void onProgressUpdate(Integer...a){
Log.d("ASYNTASK","You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
// here you can perform all action after getting resonances from RESTful service
Log.d(""+result);
}
}
Try to implement code like this:
ProgressDialog progressDialog=null;
private class LoadApi extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
progressDialog=ProgressDialog.show(YourActivity.this, "",
"Please wait...");
super.onPreExecute();
}
protected String doInBackground(String... urls) {
//Do your api call stuff here
return null;
}
protected void onPostExecute(String result) {
handle response from api call here.
progressDialog.dismiss();
}
}
If you needed a external library for http services.You can use Android Asynchronous Http Client
http://loopj.com/android-async-http/
downloaded the jar file from the link use this method
public void getData(String URL)
{
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(30000);
client.get(URL, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(String arg0)
{
// TODO Auto-generated method stub
super.onSuccess(arg0);
}
#Override
public void onFailure(Throwable arg0, String arg1)
{
// TODO Auto-generated method stub
super.onFailure(arg0, arg1);
}
});
}
You got the result as a string in the onsucess.
in your manifest file u have to given the permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Related
I want to POST JSON data having nested objects in it with the help of Asynctask in android studio, but I don't have good knowledge of API implementation in android studio. I am all new in android studio. I have successfully POST this data from POSTMAN, but I am not able to implement the code for it, also I don't have any tutorials for Asynctask. Please help me to implement code for this.
This is my Json data having nested Objects in it:
You don't need Async, Volley does it in the background for you. Put your JSONObject in the method instead of 'new JSONObject'. And YourURL - i.e '/api/route/'.
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest request_json = new JsonObjectRequest(YourURL, new JSONObject(params)),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//Do what you want on response
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//If there's an error...
}
});
//Add process to queue to get JSON in background thread
queue.add(request_json);
Nowadays a better/simpler approach would be to use a libary like Retrofit to do all the magic for you.
You can simply send a Java instance model to an API endpoint. Retrofit takes care of converting it to json when using the GsonConverterFactory class and sends the json to the endpoint you provided with the given HTTP method.
Best and Simple Library for Implementation for API services by third party library made by Square, Retrofit a Easy HTTP Client.
Why Retrofit? because, Retrofit automatically creates the background thread ,Parse the Json using GSON converter and get a call success and Failure call back directly on main thread. Without writing too much boiler plate code of AsyncTask and Parsing JSON and getting the result on main thread.
Make Retrofit Client.
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.build();
RetrofitInterface service = retrofit.create(RetrofitInterface.class);
Make Method in RetrofitInterface.
#POST("users/new")
Call<User> yourMethod(#Body UserType user);
Now Call your method and It will make your success and Failure Callback method
Call<List<Repo>> repos = service.yourMethod("octocat");
And then Call enque method to automatic create background thread.
repos.enqueue(new Callback<List<Repo>>() {
#Override
public void onResponse(Call<List<Repo>> call, Response<List<Repo>> response) {
}
#Override
public void onFailure(Call<MainResponse> call, Throwable t) {
}
});
I have some problems using retrofit as my web communication interface against a php webservice contained in a worpress website - upon a call for one of the JSON API methods in the WP site I get an SSL exception on my android client even though I run over http and not https.
Here is my code -
public class RestApi {
private static final String API_URL = "https://tmc.co.nf/api";
private SmokeTalkRest service;
interface SmokeTalkRest {
#FormUrlEncoded
#POST("/get_nonce")
void getNonce(#Field("controller") String controller, #Field("method") String method, Callback<String> callback);
}
public RestApi() {
// Create a very simple REST adapter which points the GitHub API
// endpoint.
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer(API_URL).build();
// Create an instance of our GitHub API interface.
service = restAdapter.create(SmokeTalkRest.class);
}
public void getNonceForMethod(Method method, Callback<String> callback) {
service.getNonce("user", method.name(), callback);
}
}
The get nonce is called upon a button click, did someone already bumped into that?
I believe the issue you are having is your trying to call retrofit but not using the async version. The callback is probably the easiest to use.
#GET("/user/{id}")
void listUser(#Path("id") int id, Callback<User> cb);
RestAdapter restAdapter = new RestAdapter.Builder()
.setServer("baseURL")
.build();
ClientInterface service = restAdapter.create(ClientInterface.class);
Callback callback = new Callback() {
#Override
public void success(Object o, Response response) {
//do something
}
#Override
public void failure(RetrofitError retrofitError) {
}
};
service.listUser(1, callback);
How to implement an async Callback using Square's Retrofit networking library
Android now requires you to do any webrequests async otherwise it will error out.
Also, retorfit will convert/parse the object for you so you dont have to. It saves time when it comes to creating async tasks and setting up the parsing. It also give a nice standard to go by when doing requests as well.
I am developing an android app that uses Android Async. I am using this library called Android Asynchronous Http Client
I made a method for a GET request
public String getVenues(String token) throws Exception {
AsyncHttpClient venuesReq = new AsyncHttpClient();
venuesReq.addHeader("Authorization", "Token token=" + token);
venuesReq.get(mainAct.httpRequestURL + "/venues", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
venues = response;
}
#Override
public void onFinish() {
// Completed the request (either success or failure)
}
return venues;
}
but when I call getVenues("token") the return is null, but when I try to call getVenues("token") after few seconds there are now results for venues.
I know that I am using async request so the venues doesn't return immediately.
Now what I want is, when I call getVenues("token") method there should be a returned response for the GET Request.
You need to use interface here take a look at this
https://stackoverflow.com/a/21773406/472336
Your class from where you are listening/asking for asyntask result need to impliment interface and call that interface method from asyntask..
Hope this helps
I'm using The Loopj Android Asynchronous HTTP Client to send multiple HTTP requests asynchronously.
I'm using a static AsyncHttpClient as suggested and sending multiple HTTP posts and receiving responses on an anonymous class. The problem is that when a request comes back I don't know how to tie it back to the original request.
For instance, in a caching situation, when I send a post and receive a 200 OK I need to be able to know which request that response is for so I can mark it as successfully sent.
Try this:
public class MyAsyncHttpResponseHandler extends AsyncHttpResponseHandler {
private String requestId;
public AsyncHttpResponseHandler(String requestId) {
this.requestId = requestId;
}
#Override
public void onSuccess(String arg0)
{
super.onSuccess(arg0);
// Use requestId here
}
}
Sending request:
client.get(url, new MyAsyncHttpResponseHandler(requestId))
I am developing an Android app using Parse.com website. In which whatever user sends data that must be received by receiver, but here I have to use REST api. I succeeded to send data to Parse website but now I have to Push that data with the help of REST api only. I am confused with REST api. Help to solve it.
You can use a library for that. I would suggest this one https://github.com/kodart/Httpzoid
It has clean API and type-safe data.
Here is a simple usage example
Http http = HttpFactory.create(context);
http.post("http://example.com/users")
.data(new User("John"))
.execute();
Or more complex with callbacks
Http http = HttpFactory.create(context);
http.post("http://example.com/users")
.data(new User("John"))
.handler(new ResponseHandler<Void>() {
#Override
public void success(Void ignore, HttpResponse response) {
}
#Override
public void error(String message, HttpResponse response) {
}
#Override
public void failure(NetworkError error) {
}
#Override
public void complete() {
}
}).execute();
It is fresh new, but looks very promising.