What best practices when implementing requests?

Asked

Viewed 694 times

10

When implementing calls to a webservice I have been working with the following scheme: I implement a class that extends AsynkTask and within the method doInBackground() make the call to my service. A peculiarity here, is that instead of using the class HttpUrlConnection I’ve been using a framework spring, Spring for Android, which provides a number of facilities, among them the cohesion of the code.

Although it works perfectly this scheme is somewhat unproductive and even tiring. Because, for each request need to implement a new AsyncTask.

Is there any good practice, even unofficial, or some approach that the community has adopted in order to facilitate the development of calls to a webservice and decrease the amount of code implemented for this purpose?

  • See if this answer helps you http://answall.com/questions/53758/comunica%C3%A7%C3%A3o-do-app-com-servidor-web/53761#53761

3 answers

10

If you are using JSON, you can use Retrofit to make the requests. In Retrofit it is possible to make synchronous and asynchronous calls in case of asynchronous calls (outside the Uithread), you would need to do something like this:

// Annotation para especificar uma requisição ao webservice
@GET("/usuarios/{id}/compra")

// Nome do método que fará a requisição
void getCompraUsuario(@Path("id") int id, Callback<Compra> callback);

In that case, the method getCompraUsuario make the request to the webservice and send the reply to the callback, that returns the user’s purchase.

3

There are several ways of making requests to Webservices, through code that in the case would become too extensive or through Apis, a very simplified way of making such requests are in these ways:

http://pt.slideshare.net/AlexandreAntunes3/consumindo-dados-via-web-service-no-android

http://zbra.com.br/2011/03/30/consumindo-web-service-em-aplicacoes-android/

Remember that there are methods using REST with PHP as well.

Note that there is a very good framework called "Spring", it is very dynamic and reliable! Check the second link to use it. If you want to understand how it works and how to implement a Webservice in a simplified way, see the second link. I hope I helped! Thank you.

3

Currently Android has adopted the library for HTTP requests from java.net. The recommended libraries before this were in the apache package. Google, along with AOSP, are developing a library called Volley very light and powerful. I recommend you use Volley which in the near future will be the default library for web request, but it is important to know the difference between them. In that link has a very interesting comparison about Volley and Retrofit (mentioned by the regmoraes above). But nothing better than comparing libraries in specific cases.

See also how to add Vooley as a dependency on Gradle (android-Volley).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.