Retrofit

Retrofit纯小白教学

介绍

Retrofit和OkHttp都是由Square公司开发并开源共享的网络框架。Retrofit是基于OkHttp,并支持RESTful API设计风格。它的网络请求工作实际由OkHttp完成,而Retrofit主要负责请求接口的封装。

Github文档:https://github.com/square/retrofit

Retrofit官网:https://square.github.io/retrofit/

后端接口文档一般包括这几部分:

image-20220317141541261

1.准备工作

第一步、添加依赖

retrofit2.0一定会用到的:

implementation 'com.squareup.retrofit2:retrofit:2.9.0'

可能会用到的依赖(Gson,okhttp3,converter):

implementation 'com.google.code.gson:gson:2.8.9'
implementation 'com.squareup.okhttp3:okhttp:3.1.2'
implementation 'com.squareup.retrofit2:converter-gson:2.0.1'

第二步、添加网络权限

<uses-permission android:name="android.permission.INTERNET"/>

第三步、添加网络配置

在res文件目录下,添加xml文件夹,在该文件夹中添加xml类型的配置文件(File name命名是下划线,root element是短横线):

image-20220317140122977

image-20220317140005328

<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:android="http://schemas.android.com/apk/res/android">
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

创建好之后,在AndroidManifest.xml配置文件的application标签内中添加代码:

android:networkSecurityConfig="@xml/network_security_config"

第二步、第三步完成结果是这样的:

Screenshot 2022-03-17 140341

2.创建Retrofit对象

用构建者模式创建Retrofit实例

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://101.43.122.93:8080/")
        .build();

注意:baseUrl里的参数必须以 / 结尾否则会抛出异常 IllegalArgumentException

3.创建Java接口

  • 接口分两种情况:

    ​ 1.GET 只需要获取数据

    ​ 2.POST 需要发送数据给后台

  • POST请求又分为3种情况:

    ​ 1、json请求 RequestBody

    ​ 2、表单请求 FormBody

    ​ 3、文件请求 MultipartBody

(这里以给后端传入Json格式对象,请求方法为post为例)

新建一个Java文件选择类型Interface

public interface HttpBinService {

    @POST("admin/login/")  // POST注解 表明http的请求方法,后面参数和baseurl组合成一个完整的请求路径
    @Headers({"Content-Type: application/json;charset=UTF-8"})   // 添加请求头参数
    Call<ResponseBody> postData(@Body RequestBody data);  // 请求体为 RequestBody 类型
}

注意:导包时Call是用Retrofit的包,RequestBody和ResponseBody都是okhttp3的

image-20220317144607814

4.接口实例化

HttpBinService httpBinService = retrofit.create(HttpBinService.class);

5.转换JSON格式

一般后端对接都要求传入JSON格式的字段,对于安卓,一般用两种方式进行JSON字段的打包——JSONObject 和 Gson。

Json格式常用的几种,例如:

①json数据:

{
	"age":30,
	"name":"张三",
	"isstudent”:true 
}

②json对象嵌套:

{
    "data": {
        "account": "974500760@qq.com",
        "password": "test123"
    }
}

③json数组:

["张三", "李四","王五" ]

④json对象数组:

{
    "param":"param"
    "data": [
        {
            "id": 1,
            "name": "高数",
            "number": "#CS000001",
            "tId": 1,
            "term": "202020211"
        },
        {
            "id": 2,
            "name": "离散数学",
            "number": "#CS000002",
            "tId": 1,
            "term": "202020211"
        }
    ]
}

以②为例,创建JSONObject对象:

JSONObject json = new JSONObject();
JSONObject data = new JSONObject();
try{
    data.put("account","974500760@qq.com");
    data.put("password","test123");
    json.put("data",data);
} catch (JSONException e) {
    e.printStackTrace();
}

或者也可以使用Gson:

①添加前文的Gson依赖

②创建Json对应的类

public class MyClass {
    public MyClass(Data data) {
        this.data = data;
    }
    
    public Data data;  //class是java关键词,我们不能给变量起名为class

    public static class Data {
        public String account;
        public String password;

        public Data(String account, String password) {
            this.account = account;
            this.password = password;
        }
    }
}

③实例化类,传入toJson方法

// Gson转换(类转JSON)
MyClass.Data data = new MyClass.Data("974500760@qq.com","test123");
MyClass req = new MyClass(data);
Gson gson = new Gson();
String json = gson.toJson(req);

6.接口调用

// 使用MediaType指定Json类型
MediaType jsonType = MediaType.parse("application/json; charset=utf-8");
// 创建请求体,传入json变量,构成请求体
RequestBody requestBody = RequestBody.create(jsonType, json);
// 调用接口方法,同时创建Call对象,传给call
retrofit2.Call<ResponseBody> call = httpBinService.postData(requestBody);

7.发送网路请求

// 用法基本和okhttp3的如出一辙
call.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
        String result = null;
        try {
            result = response.body().string();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if(result!=null){
            
        }else{
            Log.i("TAG", "onResponse: "+ result);
            // 在Logcat中查看结果
        }
    }

    @Override
    public void onFailure(Call<ResponseBody> call, Throwable t) {
        t.printStackTrace();
    }
});

我们用Log.i(“TAG”, "onResponse: "+ result);查看结果:

image-20220317162854884

TIPs:

1.发送请求时,需要开启一个线程来进行操作,因为主线程容易阻塞

2.UI操作只能在主线程进行,所以要进行UI操作需要调用RunOnUIThread()方法

参考博客:

你真的会用Retrofit2吗?Retrofit2完全教程 - 简书 (jianshu.com)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Retrofit是一个非常流行的网络请求库,支持HTTP和HTTPS协议。在使用Retrofit进行HTTPS请求时,需要进行一些配置,以确保请求的安全性。下面是使用Retrofit进行HTTPS请求的步骤: 1.在build.gradle文件中添加Retrofit和OkHttp的依赖: ```gradle implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.okhttp3:okhttp:4.9.0' ``` 2.创建OkHttpClient实例,并配置TLS: ```java OkHttpClient.Builder builder = new OkHttpClient.Builder(); ConnectionSpec spec = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS) .tlsVersions(TlsVersion.TLS_1_2) .cipherSuites( CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, CipherSuite.TLS_DHE_RSA_WITH_AES_128_GCM_SHA256) .build(); builder.connectionSpecs(Collections.singletonList(spec)); OkHttpClient client = builder.build(); ``` 3.创建Retrofit实例,并将OkHttpClient实例传入: ```java Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://example.com/") .client(client) .build(); ``` 4.创建API接口,并使用@HTTPS注解指定请求的HTTPS证书: ```java public interface ApiService { @GET("/") @HTTPS(certificates = "cert.pem") Call<String> get(); } ``` 5.发送HTTPS请求: ```java ApiService apiService = retrofit.create(ApiService.class); Call<String> call = apiService.get(); Response<String> response = call.execute(); String result = response.body(); ``` 需要注意的是,以上步骤只是简单介绍了如何使用Retrofit进行HTTPS请求,实际使用中还需要根据具体情况进行配置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

剽悍兔八哥

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值