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.
- public class WResponse {
- Serialized name (base)
- open
- a private database;
- @Serialized name/names
- open
- Private Ministry of the Interior;
- Serialized name (dt)
- open
- Fully private DT ;
- Serialized name (id)
- open
- personal identification of the integrator;
- @Serialized name/names
- open
- is String’s personal name;
- Serialized name (Code)
- open
- built-in personal code ;
- public line getBase() {
- The spine;
- }
- public void setBase(String base) {
- this.base = base;
- }
- public Main theme() {
- the return line;
- }
- public gap setMain(Main main) {
- this. client = client;
- }
- public integer getDt() {
- Countdown;
- }
- public invalid setDt(integer dt) {
- it.dt = dt ;
- }
- public integral getId() {
- Identification of the return consignment ;
- }
- public invalid setId(integer id) {
- this.id = id ;
- }
- public string getName() {
- a reverse name;
- }
- public invalid setName(String name) {
- that.name = name;
- }
- public integer getCod() {
- The return code;
- }
- public gap setCod (whole code) {
- this.code = code ;
- }
- }
- 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
- public class Main {
- Serialized name (temperature)
- open
- Double personal temperature;
- @Serialized name/names
- open
- Private double print ;
- @Serialized name (moisture)
- open
- private humidity Integer ;
- Serialized name(temp_min)
- open
- Personal Double TempMin;
- Serialized name (temp_max)
- open
- private Double tempMax ;
- @Serialized name (sea level)
- open
- double personal sea level;
- Serialized name(grnd_level)
- open
- double grndLevel personal ;
- public double getTemp() {
- Return temperature ;
- }
- public void setTemp (Double temp) {
- this.temperature = temperature;
- }
- public double getPressure() {i1}
- Counter-pressure ;
- }
- Blank the audiencePrint {
- this.pressure = pressure ;
- }
- public integer GetHumidity() {
- Make the humidity ;
- }
- filling a public void Humidity {
- this.moisture = humidity ;
- }
- public double getTempMin() {
- Back to TempMin ;
- }
- Invalid public SetTempMin (double tempMin) {
- this.tempMin = tempMin ;
- }
- public getTempMax() {
- to get back into the Max rhythm;
- }
- public empty space setTempMax(Double tempMax) {
- this.tempMax = tempMax ;
- }
- public Double getSeaLevel() {)
- Sea level reversal ;
- }
- Set of public blanksSeason level (double sea level) {
- this.seaLevel = sea level ;
- }
- public double getGrndLevel() {
- Reverse the gray level;
- }
- public invalid setGrndLevel(Double grndLevel) {
- this.grndLevel = grndLevel ;
- }
- }
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
- Basic URL – api.openweathermap.org
- 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.
- WeatherAPI public interface {
- /*
- Receives a request for information about the weather in the city, takes two parameters – the name of the city and the API key.
- */
- @GET(/data/2.5/weather)
- Call < WResponse > getWeatherByCity(@Query(q) String city, @Query(appid) String apiKey) ;
- }
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
:- /* Here we pass a string parameter which is eventually replaced at the end of the request.
- As if the passed parameter was 123, the path to the last query would be /data/2.5/123/getDetails.
- */
- @GET(/data/2.5/{movie_id}/getDetails)
- 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.- /* Here we send a POST request with two fields as parameters of the requesting agency POST */.
- @POST(/data/2.1)
- 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:- /*
- This request consists of obtaining information about the user by passing the user ID in the header.
- */
- @Headers (User ID: 17E9817988718E7187E710E)
- @GET(/data/2.1/user)
- 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
- NetworkClient public class {
- public static end line BASE_URL = http://api.openweathermap.org ;
- Static social modernisation;
- /*
- This public static method gives the renovation customer
- wherever he is
- */
- receives the publicly available static upgrade RetrofitClient() {
- // If this condition ensures that we do not make multiple copies of the change in the same application.
- if (retrofit == zero) {
- // Define the conversion with the manufacturer //
- upgradefit = new Retrofit.Builder()
- .baseUrl(BASE_URL) // This is the only mandatory call for the Builder object.
- .addConverterFactory(GsonConverterFactory.create()) // Conversion Library used to convert a reply to a POJO.
- .build() ;
- }
- a reverse upgrade;
- }
- }
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.
- <Relative determination
- xmlns:android=http://schemas.android.com/apk/res/android
- xmlns:tools=http://schemas.android.com/tools
- android: layout_width=match_parent
- android: layout_height=match_parent
- tools:context=com.example.irshadkumail.retro.MainActivity>.
- <Edit the text
- android:[email protected]+id/ city_name
- android: layout_width=180dp
- android: layout_height=wrap_content
- android: layout_centerHorizontal=true
- android: layout_marginTop=32dp
- android:hint= Enter the name of the city />
- <button
- android: [email protected]+id/city_click
- android: layout_width=180dp
- android: layout_height=wrap_content
- android: [email protected]/city name
- android: layout_centerHorizontal=true
- android: layout_margin=32dp
- android: text= Weather />
- <View the text
- android:[email protected]+id/answer_text
- android: layout_width=match_parent
- android: layout_height=match_parent
- android: [email protected]/city_click />
- </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.
- the MainActivity public class expands AppCompatActivity {
- Private EditText EditText ;
- personal button ;
- the private response text TextView ;
- @Overwrite
- protected hole onCreate(Bundle storedInstanceState) {
- create super.onCreate(savedInstanceState) ;
- setContentView(R.layout.activity_main) ;
- initiate();
- }
- private void init() {
- editText = findViewById(R.id.city_name) ;
- Button = findViewById(R.id.city_click) ;
- responseText = findViewById(R.id.response_text) ;
- button.setOnClickListener(new view.OnClickListener() {)
- @Overrite
- click on public blank (display v) {
- fetchWeatherDetails() ;
- }
- });
- }
- private void fetchWeatherDetails() {
- // Get an example of Retrofit by mentioning the static method
- Retrofit Retrofit = NetworkClient.getRetrofitClient() ;
- /*
- 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
- */
- WeatherAPI’s WeatherAPI’s = retrofit.create(WeatherAPI’s.class) ;
- /*
- 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.
- */
- Call = weatherAPIs.getWeatherByCity(editText.getText().toString(), 235bef5a99d6bc6193525182c409602c) ;
- /*
- 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.
- */
- call.enqueue(new callback() {)
- @Overrite
- publicly invalidated onResponse {.
- /*It’s a successful recall. Although the answer type is JSON, with Retrofit we get the answer as a WResponse POJO class.
- */
- as (answer.body() != zero) {
- WAntwort wAntwort = Antwort.body() ;
- responseText.setText(Temp: + wResponse.getMain().getTemp() + \n +
- Humidity: + wResponse.getMain().getHumidity() +
- Print : + wResponse.getMain().getPressure() ;
- }
- }
- @Overwrite
- public disability OnFailure (call, throwable t) {
- /*
- Error reminder
- */
- }
- });
- }
- 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.
android retrofit post json example,retrofit post form data example
