Connect with us

Hi, what are you looking for?

Latest

Retrofit Android Example: HTTP GET, POST Request

Retrofit Android Example: HTTP GET, POST Request

In our last tutorial we discussed how to send a network request using the Volley library. Although Volley is a widely used network library for basic HTTP operations, there is another library that is very popular among Android developers –Retrofit. In fact, many developers prefer the on-the-fly upgrade because of its ease of use, performance, scalability, and so on.

Retrofit is essentially an HTTP client for Android and Java, developed by some great people at Square. By default, OKHttp is used for network operations. What’s special about Retrofit is that you don’t have to worry about the response analysis, which means that deserialization is processed in the background. Just configure a library of converters (GSON, Jackson, etc.) and you’re done.

In this example we are developing an application that sends a network request from Retrofit and displays the answer. We will use the OpenWeather API to get up-to-date weather information. This is a free API service that provides a set of APIs for detailed weather information from around the world. All you have to do is register to receive an API key. For more information

API:
https://api.openweathermap.org/data/2.5/weather?q=London,uk

JSON example answer

{coordinates:{lon:-0,13,lat:51,51}, weather: [{id:300,main:drizzle,description:light drizzle,icon:09d}],base:{temp:280,32,pressure:1012,humidity:81,temperature_min:279,15,rate_max:281.15},visibility:10000,wind:{speed:4.1,deg:80},clouds:{all:90},dt:1485789600,sys:{type:1,id:5091,message:0.0103,land:GB,sunrise:1485762037,sunset:1485794875},id:2643743,name:London,code:200}.

Step 1: Dependence on imported conversion

As always, the first step is to add the necessary dependencies to the build.gradle file.

compile com.squareup.retrofit2:retrofit:2.4.0.

In addition to adjusting the client dependency, we also need to add a converter library, depending on how we want to deserialize the response. The different types of inverters are listed below

  • Gson : com.squareup.retrofit2:converter-gson
  • Jackson : com.squareup.retrofit2:jackson converter
  • Moshi : com.squareup.retrofit2:moshi converter
  • Protobuf: com.squareup.retrofit2: prototype inverter
  • Wire: com.squareup.retrofit2: Wire converter
  • Simple XML: com.squareup.retrofit2: converter-simplexml
  • Scars (primitives, box and lower case) : com.squareup.retrofit2:Converting scars

For this example, I’ll use Gson.

Step 2: Establishment of the TOBO

As I said, modernisation itself is responsible for the deserialisation of the answer. But to make this possible, we need to create a POJO (Plain Old Java Objects) for the JSON response on the lines with the used converter library.

A very simple way to create a POJO to respond is available on this site. Just insert the answer and select an annotation scheme, and a POJO will be created with the annotations compatible with the selected library.

  • In this example, we use the Gson library for deserialization. So, when making a POJO, I added a note @SerializedName . This annotation compares this variable with the corresponding key in the JSON answer.
  1. public class WResponse {
  2. Serialized name (base)
  3. open
  4. a private database;
  5. @Serialized name/names
  6. open
  7. Private Ministry of the Interior;
  8. Serialized name (dt)
  9. open
  10. Fully private DT ;
  11. Serialized name (id)
  12. open
  13. personal identification of the integrator;
  14. @Serialized name/names
  15. open
  16. is String’s personal name;
  17. Serialized name (Code)
  18. open
  19. built-in personal code ;
  20. public line getBase() {
  21. The spine;
  22. }
  23. public void setBase(String base) {
  24. this.base = base;
  25. }
  26. public Main theme() {
  27. the return line;
  28. }
  29. public gap setMain(Main main) {
  30. this. client = client;
  31. }
  32. public integer getDt() {
  33. Countdown;
  34. }
  35. public invalid setDt(integer dt) {
  36. it.dt = dt ;
  37. }
  38. public integral getId() {
  39. Identification of the return consignment ;
  40. }
  41. public invalid setId(integer id) {
  42. this.id = id ;
  43. }
  44. public string getName() {
  45. a reverse name;
  46. }
  47. public invalid setName(String name) {
  48. that.name = name;
  49. }
  50. public integer getCod() {
  51. The return code;
  52. }
  53. public gap setCod (whole code) {
  54. this.code = code ;
  55. }
  56. }
  • You may have noticed that my POJO does not contain variables for many parameters in the JSON answer (only the JSON keys defined in WResponse.java are deserialized). I ignored the JSON objects that are useless in this example, so we avoided creating a lot of Java classes.
  • The only other POJO I’m gonna make is Main.java. This is the master key JSON The subject of the answer
  1. public class Main {
  2. Serialized name (temperature)
  3. open
  4. Double personal temperature;
  5. @Serialized name/names
  6. open
  7. Private double print ;
  8. @Serialized name (moisture)
  9. open
  10. private humidity Integer ;
  11. Serialized name(temp_min)
  12. open
  13. Personal Double TempMin;
  14. Serialized name (temp_max)
  15. open
  16. private Double tempMax ;
  17. @Serialized name (sea level)
  18. open
  19. double personal sea level;
  20. Serialized name(grnd_level)
  21. open
  22. double grndLevel personal ;
  23. public double getTemp() {
  24. Return temperature ;
  25. }
  26. public void setTemp (Double temp) {
  27. this.temperature = temperature;
  28. }
  29. public double getPressure() {i1}
  30. Counter-pressure ;
  31. }
  32. Blank the audiencePrint {
  33. this.pressure = pressure ;
  34. }
  35. public integer GetHumidity() {
  36. Make the humidity ;
  37. }
  38. filling a public void Humidity {
  39. this.moisture = humidity ;
  40. }
  41. public double getTempMin() {
  42. Back to TempMin ;
  43. }
  44. Invalid public SetTempMin (double tempMin) {
  45. this.tempMin = tempMin ;
  46. }
  47. public getTempMax() {
  48. to get back into the Max rhythm;
  49. }
  50. public empty space setTempMax(Double tempMax) {
  51. this.tempMax = tempMax ;
  52. }
  53. public Double getSeaLevel() {)
  54. Sea level reversal ;
  55. }
  56. Set of public blanksSeason level (double sea level) {
  57. this.seaLevel = sea level ;
  58. }
  59. public double getGrndLevel() {
  60. Reverse the gray level;
  61. }
  62. public invalid setGrndLevel(Double grndLevel) {
  63. this.grndLevel = grndLevel ;
  64. }
  65. }

Step 3 – Identification of HTTP endpoints

The upgrade splits the URL of the network request into two parts: the base URL and the end point (path). As in this case, the entire end point

http://api.openweathermap.org/data/2.5/weather

  1. Basic URL – api.openweathermap.org
  2. Directions – /data/2.5/ Weather

All endpoints of an HTTP request must be defined in the interface as shown below. Each method on the interface represents an endpoint and must specify the type of application, the application parameters and the header lines with comments. In this example, we send only one GET request, so we define only one method.

  • All methods must return a call object that is executed to send a network request and answer.
  • T in the call is a POJO class (in this case WResponse) to which the answer must be deserialised.
  1. WeatherAPI public interface {
  2. /*
  3. Receives a request for information about the weather in the city, takes two parameters – the name of the city and the API key.
  4. */
  5. @GET(/data/2.5/weather)
  6. Call < WResponse > getWeatherByCity(@Query(q) String city, @Query(appid) String apiKey) ;
  7. }

URL manipulation

With the update you can easily change an HTTP request using notes. The different types of comments are listed below.

  • Request Types – This note specifies the HTTP request type
    Example @GETTUNG, @POST, @INPUT, @DELETE.
  • @ Request
    This note specifies all key values for requests to be sent with a network request.
  • @ path
    This note assumes that the transferred parameter is replaced in the example of the endpoint of path
    :
    1. /* Here we pass a string parameter which is eventually replaced at the end of the request.
    2. As if the passed parameter was 123, the path to the last query would be /data/2.5/123/getDetails.
    3. */
    4. @GET(/data/2.5/{movie_id}/getDetails)
    5. Call < T > getMovieDatils(@Path(movie_id) String movieID) ;
  • @ field
    Used in the POST request. You define the parameters in the main part of the POST request.
    1. /* Here we send a POST request with two fields as parameters of the requesting agency POST */.
    2. @POST(/data/2.1)
    3. Call < T > postMovieDetails(@field(userId) string userID, @field(token) string token) ;
  • @Chapters
    This note is a random heading to be encoded with the request.
    For example:
    1. /*
    2. This request consists of obtaining information about the user by passing the user ID in the header.
    3. */
    4. @Headers (User ID: 17E9817988718E7187E710E)
    5. @GET(/data/2.1/user)
    6. Call < T > fetchUserDetails()

Step 4: Creating a customer for reconstruction

We defined the endpoints and also created a POJO based on JSON’s reaction. All we have to do is convert our interface methods into a callable network request that can be executed. Here comes Retrofit.Builder() .

The retrofit object is used to adapt the Java interface to HTTP calls by annotating the declared methods. Create instances with the constructor and provide your interface to create the implementation (java.lang.Class).

  • Create a NetworkClient.java class using a static method that returns an instance of the upgrade object, as shown below
  1. NetworkClient public class {
  2. public static end line BASE_URL = http://api.openweathermap.org ;
  3. Static social modernisation;
  4. /*
  5. This public static method gives the renovation customer
  6. wherever he is
  7. */
  8. receives the publicly available static upgrade RetrofitClient() {
  9. // If this condition ensures that we do not make multiple copies of the change in the same application.
  10. if (retrofit == zero) {
  11. // Define the conversion with the manufacturer //
  12. upgradefit = new Retrofit.Builder()
  13. .baseUrl(BASE_URL) // This is the only mandatory call for the Builder object.
  14. .addConverterFactory(GsonConverterFactory.create()) // Conversion Library used to convert a reply to a POJO.
  15. .build() ;
  16. }
  17. a reverse upgrade;
  18. }
  19. }

Step 5: Send request

Now here’s the important part: sending the Retrofit HTTP GET request and displaying the answer.

  • Our user interface contains only one EditText and one button. Enter the name of the city in EditText and click the button. If you click on it, you will receive an online request for detailed information about the weather in that city.
  1. <Relative determination
  2. xmlns:android=http://schemas.android.com/apk/res/android
  3. xmlns:tools=http://schemas.android.com/tools
  4. android: layout_width=match_parent
  5. android: layout_height=match_parent
  6. tools:context=com.example.irshadkumail.retro.MainActivity>.
  7. <Edit the text
  8. android:id=@+id/ city_name
  9. android: layout_width=180dp
  10. android: layout_height=wrap_content
  11. android: layout_centerHorizontal=true
  12. android: layout_marginTop=32dp
  13. android:hint= Enter the name of the city />
  14. <button
  15. android: id=@+id/city_click
  16. android: layout_width=180dp
  17. android: layout_height=wrap_content
  18. android: layout_below=@id/city name
  19. android: layout_centerHorizontal=true
  20. android: layout_margin=32dp
  21. android: text= Weather />
  22. <View the text
  23. android:id=@+id/answer_text
  24. android: layout_width=match_parent
  25. android: layout_height=match_parent
  26. android: layout_below=@id/city_click />
  27. </RelativeLayout>
  • We already have a Java interface that defines a GET request. Using the update instance returned by NetworkClient , we now create a callable object of the annotation-based interface method defined with it. For more information, see the following code snippet.
  1. the MainActivity public class expands AppCompatActivity {
  2. Private EditText EditText ;
  3. personal button ;
  4. the private response text TextView ;
  5. @Overwrite
  6. protected hole onCreate(Bundle storedInstanceState) {
  7. create super.onCreate(savedInstanceState) ;
  8. setContentView(R.layout.activity_main) ;
  9. initiate();
  10. }
  11. private void init() {
  12. editText = findViewById(R.id.city_name) ;
  13. Button = findViewById(R.id.city_click) ;
  14. responseText = findViewById(R.id.response_text) ;
  15. button.setOnClickListener(new view.OnClickListener() {)
  16. @Overrite
  17. click on public blank (display v) {
  18. fetchWeatherDetails() ;
  19. }
  20. });
  21. }
  22. private void fetchWeatherDetails() {
  23. // Get an example of Retrofit by mentioning the static method
  24. Retrofit Retrofit = NetworkClient.getRetrofitClient() ;
  25. /*
  26. The main goal of the upgrade is to create HTTP calls from the Java interface based on the annotations of each method. To do this, all you have to do is pass the interface class as a parameter when creating the
  27. */
  28. WeatherAPI’s WeatherAPI’s = retrofit.create(WeatherAPI’s.class) ;
  29. /*
  30. Call the method corresponding to the HTTP request to return the call object. The Call object is used to send a real network request with the specified parameters.
  31. */
  32. Call = weatherAPIs.getWeatherByCity(editText.getText().toString(), 235bef5a99d6bc6193525182c409602c) ;
  33. /*
  34. This is a chain that actually sends a request to the network. The query() call executes the call asynchronously. It has two inverted listeners called on the main stream.
  35. */
  36. call.enqueue(new callback() {)
  37. @Overrite
  38. publicly invalidated onResponse {.
  39. /*It’s a successful recall. Although the answer type is JSON, with Retrofit we get the answer as a WResponse POJO class.
  40. */
  41. as (answer.body() != zero) {
  42. WAntwort wAntwort = Antwort.body() ;
  43. responseText.setText(Temp: + wResponse.getMain().getTemp() + \n +
  44. Humidity: + wResponse.getMain().getHumidity() +
  45. Print : + wResponse.getMain().getPressure() ;
  46. }
  47. }
  48. @Overwrite
  49. public disability OnFailure (call, throwable t) {
  50. /*
  51. Error reminder
  52. */
  53. }
  54. });
  55. }
  • As you may have noticed, the response reminder called on the main wire comes with a WResponse object that automatically analyzes the JSON response. This is because when defining a method in the interface, we specify the type of return as a call.
  • You may be aware that Android does not allow network operations on the main stream, so the upgrade itself switches to the background stream. In the main stream, however, memories of the answer are evoked.
  • With a simple click an HTTP request is made and information about the weather is requested.  We don’t do much with the resulting details, we just show them on the screen. I didn’t use a very trendy interface to display the details, because our main task in this article is to send network requests via Retrofit. Retrofit Android Example: HTTP GET, POST Request

 

 

 

 android retrofit post json example,retrofit post form data example

You May Also Like

Copyright © 2020 Digimetriq's Empire. Sitemap