Operation mode of Retrofit2 under Kotlin project

Keywords: Retrofit network Android Java

Reference blog: http://blog.csdn.net/carson_ho/article/details/73732076
GitHub address: https://github.com/yangtianfu2018/Retrofit2Project
Code implementation steps:

Add dependency:

Network request permission, no longer more, depends on the following:

 implementation 'com.squareup.retrofit2:retrofit:2.0.2'
    // Retrofit Library
    implementation 'com.squareup.okhttp3:okhttp:3.1.2'
    // Okhttp Library
    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
//    Data parser

Establish entity class to obtain network return data


The code is quite simple. It's OK to use kotlin to build entity classes. Android studio 3.0 and above can be converted automatically

Describe the interface of the network request

get mode:

package com.ytf.ppg.retrofit2application.retrofit;

import com.ytf.ppg.retrofit2application.bean.Translation;

import retrofit2.Call;
import retrofit2.http.GET;

/**
 * Created by ppg on 2018/3/9.
 */

public interface GetRequest_Interface {
    @GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")//Relative path after passing BaseURL
    Call<Translation> getCall();
    // Retrofit divides the URL of the network request into two parts: one is placed in the retrofit object, the other is placed in the network request interface
    // If the URL in the interface is a complete URL, the URL in the Retrofit object can be ignored
    // getCall() is a method to accept data from network requests

}

Post mode:

package com.ytf.ppg.retrofit2application.retrofit;


import com.ytf.ppg.retrofit2application.bean.TranslationPost;

import java.util.ResourceBundle;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * Created by ppg on 2018/3/9.
 * Describe the interface of the network request
 */

public interface PostRequest_Interface {
    @POST("translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=")
    @FormUrlEncoded
    Call<TranslationPost> getCall(@Field("i") String target);
}

Action to initiate request:

package com.ytf.ppg.retrofit2application.acvitity

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.ytf.ppg.retrofit2application.R
import com.ytf.ppg.retrofit2application.bean.Translation
import com.ytf.ppg.retrofit2application.bean.TranslationPost
import com.ytf.ppg.retrofit2application.retrofit.GetRequest_Interface
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import com.ytf.ppg.retrofit2application.retrofit.PostRequest_Interface




class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        requestByGet()
        requestByPost()
    }

    /**
     * get Mode request
     */
    private fun requestByGet() {
    //step4:Establish Retrofit object
        val retrofit = Retrofit.Builder()
                .baseUrl("http://fy.iciba.com/") // Set network request Url
                .addConverterFactory(GsonConverterFactory.create()) //Set to use Gson resolution (remember to add dependency)
                .build()

        // step5:Create an instance of the network request interface
        val request = retrofit.create(GetRequest_Interface::class.java)

        //Encapsulate send request
        val call = request.call

        //step6:Send network request(asynchronous)
        call.enqueue(object : Callback<Translation> {
            //Callback on successful request
            override fun onResponse(call: Call<Translation>, response: Response<Translation>) {
                // step7: Processing returned data results
                response.body().show()
            }

            //Callback on request failure
            override fun onFailure(call: Call<Translation>, throwable: Throwable) {
                println("connection failed")
            }
        })
    }

    /**
     * post Mode request
     */
    private fun requestByPost() {
        //step4:Establish Retrofit object
        val retrofit = Retrofit.Builder()
                .baseUrl("http://fanyi.youdao.com/") // Set network request Url
                .addConverterFactory(GsonConverterFactory.create()) //Set to use Gson resolution (remember to add dependency)
                .build()

        // step5:Create an instance of the network request interface
        val request = retrofit.create(PostRequest_Interface::class.java)

        //Encapsulate the sending request (set the content to be translated)
        val call = request.getCall("I love you")

        //step6:Send network request(asynchronous)
        call.enqueue(object : Callback<TranslationPost> {

            //Callback on successful request
            override fun onResponse(call: Call<TranslationPost>, response: Response<TranslationPost>) {
                // step7: Process the returned data result: output the translated content
                System.out.println(response.body().getTranslateResult().get(0).get(0).getTgt())
            }

            //Callback on request failure
            override fun onFailure(call: Call<TranslationPost>, throwable: Throwable) {
                println("request was aborted")
                println(throwable.message)
            }
        })
    }

}

Posted by skiingguru1611 on Wed, 01 Apr 2020 17:36:14 -0700