Retrofit2 for Android network request (1)

Foreword: I have used Retrofit for such a long time to record it now. This article is a simple method of use, and will continue to be updated in the future. This article is suitable for novices, and veterans can give some advice

Don't talk nonsense, let's go straight

The first is to import the required packages, don't forget to click sync

implementation 'com.squareup.okhttp3:okhttp:3.1.2'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'

1. Transform your okhttp request into a java interface, use annotations to describe and configure network request parameters, and encapsulate Url addresses and network data requests

public interface ApiService{
        @GET("getAll")
        Call<ResponseBody> getAll(@Query("key") String key, @Query("consName") String consName, @Query("type") String type);
    }

Here I take my aggregation interface as an example to illustrate

@GET ----- The get request indicated (see Table 1 for details)

The getAll ----- in ("getAll") indicates the requested address (that is, the address added after the url, which is part of the url). Is it combined with baseUrl to be the full path request address, such as URL=" http://web.juhe.cn:8080/constellation/", the requested address is getall, then the combined full path is "http://web.juhe.cn:8080/constellation/getAll"

The Bean in Call<Bean> ----- represents our custom Bean class, which can also be written as ResponseBody. This is usually used when testing or when the returned content is not clear. It directly returns String shape type data

getAll ----- means the method name, we can freely define the method name

@Query("key") String key ----- @Query represents the request parameter annotation, ("key") represents the request parameter field of the interface, String is not much said to be the parameter type, and the key behind it is the field value (see Table 2 for details)

 Table 1 request method annotation

request method annotation illustrate
@GET get request
@POST post request
@PUT put request
@DELETE delete request
@PATCH patch request, which is a supplement to the put request and used to update local resources
@HEAD head request
@OPTIONS options request
@HTTP Through annotations, all the above annotations can be replaced, it has three attributes: method, path, hasBody

 Table 2 request parameter annotation

Request parameter annotation illustrate
@Body It is mostly used for Post requests to send non-expressive data. According to the conversion method, the instance object is converted into a corresponding string to pass parameters. For example, using Post to send Json data, adding GsonConverterFactory is to convert the body into a json string for transmission
@Filed It is mostly used to pass parameters in Post mode, and it needs to be used in conjunction with @FromUrlEncoded, that is, to pass parameters in the form of a form
@FiledMap It is mostly used for form fields in Post requests and needs to be used in conjunction with @FromUrlEncoded
@Part For form fields, Part and PartMap are used in combination with the @multipart annotation, suitable for file uploads
@PartMap For form fields, the default accepted type is Map<String,RequestBody>, which can be used to upload multiple files
@Path Used for placeholders in Url
@Query Parameters used in Get requests
@QueryMap Similar to Query, used to determine form parameters
@Url Specify the request path

 Then there is the service request url, which is composed of IP and port, which is the interface provided to us by the background we often use. Remember to add "/" after the interface because things will be spliced ​​later. If you don't add it, you will report an error

public static final String Url="http://web.juhe.cn:8080/constellation/";

2. Create a Retrofit instance

Retrofit retrofit=new Retrofit.Builder().baseUrl(Url).build();

Note here that if the previous Bean uses ResponseBody, you can write it directly like this. If it is a custom Bean class, you need to add addConverterFactory(GsonConverterFactory.create()), which is the Gson converter

Retrofit retrofit=new Retrofit.Builder().baseUrl(Url).addConverterFactory(GsonConverterFactory.create()).build();

Then create an instance of the interface

ApiService apiService=retrofit.create(ApiService.class);

The next step is to call, call the method in the interface

Call<ResponseBody> call=apiService.getAll("3e4d3cb8eb07d3b06e3f6a99ae34b1ee","双子座","today");

The last is to receive the returned result

call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    System.out.println("666"+response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("33333"+call+"/n"+t.toString());
            }
        });

3. This is the complete code. Here I run it directly in the class, which is lazy

public class RetrofitText {
    //服务器请求的URL
    public static final String Url="http://web.juhe.cn:8080/constellation/";
    //定义接口
    public interface ApiService{
        @GET("getAll")
        Call<ResponseBody> getAll(@Query("key") String key, @Query("consName") String consName, @Query("type") String type);
    }

    public static void main(String[] args){
        getList();
    }
    public static void getList(){
        //创建Retrofit实例
        Retrofit retrofit=new Retrofit.Builder().baseUrl(Url).build();
        //创建接口实例
        ApiService apiService=retrofit.create(ApiService.class);
        //调用接口中的方法
        Call<ResponseBody> call=apiService.getAll("3e4d3cb8eb07d3b06e3f6a99ae34b1ee","双子座","today");
        //返回结果
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    System.out.println("返回的结果"+response.body().string());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                System.out.println("33333"+call+"/n"+t.toString());
            }
        });
    }
}

The result obtained after running

{"date":20200810,"name":"双子座","QFriend":"水瓶座","color":"水蓝色","datetime":"2020年08月10日","health":"80","love":"70","work":"80","money":"60","number":4,"summary":"请调整你处理事情的方式,你是有机会朝目标前进的,但双子座很容易在略感困难的状况下改变方向,这种消极行为尽量避免,你才能在合适的时机有收获。作者:伦敦占星学院-不卉游泳的鱼","all":"80","resultcode":"200","error_code":0}

This article is here first, and will continue to be updated later

Guess you like

Origin blog.csdn.net/lanrenxiaowen/article/details/107906623