Android---Retrofit实现网络请求:Java 版

简介

在 Android 开发中,网络请求是一个极为关键的部分。Retrofit 作为一个强大的网络请求库,能够简化开发流程,提供高效的网络请求能力。

Retrofit 是一个建立在 OkHttp 基础之上的网络请求库,能够将我们定义的 Java 接口转化为相应的 HTTP请求,Retrofit 是适用于 Android 和 Java 的类型安全 HTTP 客户端。通过Retrofit,我们可以轻松发起网络请求,还能将服务器返回的数据转换为所需的格式,如 JSON。

简单使用

1. 在 APP 目录下的 build.gradle 里添加依赖

    // retrofit
    // https://github.com/square/retrofit
    implementation("com.squareup.retrofit2:retrofit:2.9.0")
    // 适配 retrofit 使用 gson 解析
    // 版本要和 retrofit 一样
    implementation("com.squareup.retrofit2:converter-gson:2.9.0")
    // 使用 gson 解析 json
    // https://github.com/google/gson
    implementation("com.google.code.gson:gson:2.10.1")

2. 在 AndroidManifest.xml 里添加网络权限

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

3. NetworkModule.kt 创建 Retrofit 实例。单例创建Retrofit,并通过create() 方法返回一个 Service 实例。

public class NetworkModule {
    private static Retrofit newsRetrofit;

    private NetworkModule(){}

    public static <T> T getService(Class<T> newsService){
        if (newsRetrofit == null) {
            synchronized (NetworkModule.class){
                if (newsRetrofit == null) {
                    newsRetrofit = new Retrofit.Builder()
                            .baseUrl("http://v.juhe.cn/")
                            .addConverterFactory(GsonConverterFactory.create())
                            .build();
                }
            }
        }
        //TODO 通过 Retrofit 的 create() 方法返回一个传入 Service 的实例
        return newsRetrofit.create(newsService);
    }
}

getService(Class<T> newsService) 方法里,通过Retrofit.create() 方法,返回一个传入的 NewsService 的实例

4. NetworkService.kt 创建网络请求的 Service。是一个接口类

public interface NetworkService {
    @GET("toutiao/index")
    Call<NewsEntity> getNewsService(@Query("key") String key);
}

NewsEntity 是一个实体类,解析返回的数据。Result.java是一个具体的数据类,可根据返回的数据进行细化。

public class NewsEntity {

    private String reason;//返回说明, 成功为 success

    //private Result result;

    private int error_code;// 返回码

    public String getReason() {
        return reason;
    }

    public void setReason(String reason) {
        this.reason = reason;
    }

    public int getError_code() {
        return error_code;
    }

    public void setError_code(int error_code) {
        this.error_code = error_code;
    }
}

5. MainActivity.java 进行网络请求

public class MainActivity extends AppCompatActivity {

    private TextView networkRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        networkRequest = findViewById(R.id.network_request);
        networkRequest.setOnClickListener(view -> {
            // 创建 NetworkService 的实例
            NetworkService networkService = NetworkModule.getService(NetworkService.class);
            networkService.getNewsService("40279bee66d427555ce361fe49387a8e").enqueue(new Callback<NewsEntity>() {
                @Override
                public void onResponse(Call<NewsEntity> call, Response<NewsEntity> response) {
                    // TODO 请求成功
                    Log.d("HL", response.body().getReason());
                }

                @Override
                public void onFailure(Call<NewsEntity> call, Throwable t) {
                    // TODO 请求失败
                }
            });
        });
    }

}

注意:网络请求是异步操作,应该放入子线程里执行。这里为了演示请求是否成功,就简单的在 UI 线程里进行。

请求的数据是聚合数据上的新闻头条API 接口,请求地址为: "http://v.juhe.cn/toutiao/index?key=40279bee66d427555ce361fe49387a8e"。由于是使用的 http 请求头,所以需要在 AndroidManifest.xml 里添加 android:usesCleartextTraffic="true",更改网络安全配置。

最后,通过打印 Log 的方式,查看请求是否成功。 现实结果为 success。

对应的 Java 版本实现:Android---Retrofit实现网络请求:Kotlin版 

  • 9
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

别偷我的猪_09

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

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

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

打赏作者

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

抵扣说明:

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

余额充值