• Android学习笔记 38. 网络加载框架Retrofit


    Android学习笔记

    Android常用框架——网络加载框架Retrofit

    38. 网络加载框架Retrofit

    38.1 Retrofit简介

    Retrofit 是一个 RESTful 的 HTTP 网络请求框架的封装。
    原因:网络请求的工作本质上是 OkHttp 完成,而 Retrofit 仅负责 网络请求接口的封装

    官方地址:

    https://github.com/square/retrofit

    在这里插入图片描述

    最新版本

    在这里插入图片描述

    引入依赖

    在这里插入图片描述

    同步

    38.2 Retrofit基本使用

    服务器依然使用httpbin

    在这里插入图片描述

    域名:https://www.httpbin.org/

    接口:post

    参数:username, password

    接口:get

    参数:username,password

    → 根据接口创建Java接口

    package com.dingjiaxiong.myretrofit;
    
    import okhttp3.ResponseBody;
    import retrofit2.Call;
    import retrofit2.http.Field;
    import retrofit2.http.FormUrlEncoded;
    import retrofit2.http.GET;
    import retrofit2.http.POST;
    import retrofit2.http.Query;
    
    public interface HttpBinService { 
        
        @POST("post")
        @FormUrlEncoded
        Call<ResponseBody> post(@Field("username") String userName ,@Field("password") String pwd);
    
        @GET("get")
        Call<ResponseBody> get(@Query("username") String userName ,@Query("password") String pwd);
        
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    第二步:创建Retrofit对象,并生成接口实现类对象

    package com.dingjiaxiong.myretrofit;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    
    import java.io.IOException;
    
    import okhttp3.ResponseBody;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    import retrofit2.Retrofit;
    
    public class MainActivity extends AppCompatActivity {
    
    
        private Retrofit retrofit;
        private HttpBinService httpBinService;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
    
            httpBinService =retrofit.create(HttpBinService.class);
    
        }
    
        public void postAsync(View view) {
    
            Call call = httpBinService.post("dingjiaxiong", "123");
            call.enqueue(new Callback() {
                @Override
                public void onResponse(Call call, Response response) {
                    try {
                        Log.e("dingjiaxiong", "onResponse: " + response.body().string() );
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                @Override
                public void onFailure(Call call, Throwable t) {
    
                }
            });
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    布局文件

    就一个按钮

    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity"
        android:orientation="vertical"
        >
    
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="post异步请求"
            android:onClick="postAsync"
            />
    
    LinearLayout>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    一定记得在清单文件中加权限,不然会直接退出

    运行

    在这里插入图片描述

    OK

    38.3 Retrofit中的注解

    分类:

    • 方法注解:@GET , @POST , @PUT , @DELETE , @PATH , @HEAD , @OPTIONS , @HTTP
    • 标记注解:@FormUrlEncoded , @Multipart , @Streaming
    • 参数注解:@Query , @QueryMap , @Body , @FieldMap , @Part , @PartMap
    • 其他注解:@Path , @ Header , @Headers , @Url

    在这里插入图片描述

    @HTPP 注解可以自定义请求的方式。

    在这里插入图片描述

    使用上就是调方法、传参。

    参数注解@Body演示测试

    接口:

    @POST("post")
    Call<ResponseBody> postBody(@Body RequestBody requestBody);
    
    • 1
    • 2
    package com.dingjiaxiong.myretrofit;
    
    import org.junit.Test;
    
    import java.io.IOException;
    
    import okhttp3.FormBody;
    import okhttp3.ResponseBody;
    import retrofit2.Response;
    import retrofit2.Retrofit;
    
    public class AnnitationUnitTest {
    
        Retrofit retrofit = new Retrofit.Builder().baseUrl("https://www.httpbin.org/").build();
        HttpBinService httpBinService = retrofit.create(HttpBinService.class);
    
        @Test
        public void bodyTest() throws IOException {
            FormBody formBody = new FormBody.Builder()
                    .add("a", "1")
                    .add("b", "2").build();
            Response<ResponseBody> response = httpBinService.postBody(formBody).execute();
            System.out.println(response.body().string());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在这里插入图片描述

    @Path注解演示

    @POST("{id}")
    Call<ResponseBody> postPath(@Path("id") String path);
    
    • 1
    • 2
    @Test
    public void pathTest() throws IOException {
        Response<ResponseBody> response = httpBinService.postPath("post").execute();
        System.out.println(response.body().string());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    在这里插入图片描述

    实际上就是完成了一个post 请求。

    加个参数。

    在这里插入图片描述

    在这里插入图片描述

    运行

    在这里插入图片描述

    ok。

    @Header注解用于设置请求头

    演示

    再加一个参数

    在这里插入图片描述

    调用时

    在这里插入图片描述

    在这里插入图片描述

    OK

    @Headers注解

    在这里插入图片描述

    @Test
    public void headersTest() throws IOException {
        Response<ResponseBody> response = httpBinService.postWithHeaders().execute();
        System.out.println(response.body().string());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    运行

    在这里插入图片描述

    @Url注解

    在这里插入图片描述

    测试方法

    @Test
    public void UrlTest() throws IOException {
        Response<ResponseBody> response = httpBinService.postUrl("https://www.httpbin.org/post").execute();
        System.out.println(response.body().string());
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    运行

    报错了,加上@POST

    在这里插入图片描述

    再运行

    在这里插入图片描述

    请求成功。

    作用:指定一个地址,作为这次请求的一个完整的请求地址。

  • 相关阅读:
    es之null_value
    基于Springcloud搭建电商平台实现高性能高并发微服务
    【Azure上云项目实战】 合规性的身份验证与访问控制:在 Azure 中实现符合 PCI DSS 要求的架构设计
    pandas第8章-文本数据
    Android两个应用同时使用后置摄像录像
    vue-router路由知识
    Python魔术方法
    对于Java中权限修饰符的理解
    2022.09 青少年Python等级考试(六级) 选择题部分
    JS力扣第九题-回文数
  • 原文地址:https://blog.csdn.net/weixin_44226181/article/details/126296545