Retrofit 最基本搭建

该文介绍了如何在Android中使用Retrofit进行网络请求的最基本搭建,包括集成OkHttp和Gson库,设置网络权限,定义接口,使用注解指定请求方式和参数,创建Retrofit实例,以及执行同步和异步请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Retrofit 最基本搭建

1. 开源库集成

  • 依赖包导入
implementation 'com.squareup.okhttp3:okhttp:4.10.0'
implementation 'com.squareup.okio:okio-jvm:3.2.0'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
  • 网络权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

2. 创建接口设置请求类型和参数

  • 新建返回结果实体类MyResult
package cn.test.read01.pojo;

public class MyResult {

    private String message;

    private int code;

    private Object data;

    public MyResult(String message, int code, Object data) {
        this.message = message;
        this.code = code;
        this.data = data;
    }

    public MyResult() {
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

  • 创建api接口
package cn.test.read01.service;

import cn.test.read01.pojo.MyResult;
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 SysService {
    @POST("/sys/login")
    @FormUrlEncoded
    Call<MyResult> login(@Field("username") String username, @Field("password") String password);
}

常见注解

  • @GET
  • @POST
  • @PUT
  • @DELETE
  • @Path
  • @Query
  • @QueryBody
  • @Body

3. 创建Retrofit对象、设置数据解析器(gson解析器)

Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("https://readb.liuzhichao.xyz")
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();

常用数据解析器

4. 生成接口对象

SysService sysService = retrofit.create(SysService.class);

5. 调用接口方法

Call<MyResult> call = sysService.login("admin", "admin");

6. 发送请求处理返回数据

  • 同步请求
try {
    new Thread(new Runnable() {
        @Override
        public void run() {
            Response<MyResult> response = null;
            try {
                response = call.execute();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            System.out.println(response.body().getMessage());

        }
    }).start();
}catch (Exception e){
    e.fillInStackTrace();
}
  • 异步请求(call.enqueue())
call.enqueue(new Callback<MyResult>() {
    @Override
    public void onResponse(Call<MyResult> call, Response<MyResult> response) {
        System.out.println(response);
        MyResult result = response.body();
        assert result != null;
        System.out.println(result.getData());
    }

    @Override
    public void onFailure(Call<MyResult> call, Throwable t) {

    }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值