关于CTS项目的Android Retrofit

关于CTS项目的Android Retrofit

1、配置build.gradle(Module)
implementation ‘com.squareup.retrofit2:retrofit:2.4.0’
implementation ‘com.squareup.retrofit2:converter-gson:2.4.0’

2、服务端返回值
{“apkver”:”1″}

3、ApkVer.java

/**
 * CopyRright (c)2018-2028: chanpinxue.cn
 * Project: cts
 * Module Name: ApkVer
 * Comments: 版本号
 * JDK version used: JDK1.8
 * Author: jzh
 * Create Date: 2018-11-05
 * Modified By: jzh
 * Modified Date: 2018-11-05
 * Why & What is modified:
 * Version: <1.0>
 */
public class ApkVer {
    private String apkver;

    public String getApkver() {
        return apkver;
    }

    public void setApkver(String apkver) {
        this.apkver = apkver;
    }

    //
    public void show() {
        System.out.println( "apkver:"+ apkver);
    }
}

4、WebAPI.java

package cn.mf.cts.retrofit;

import retrofit2.Call;
import retrofit2.http.GET;

/**
 * CopyRright (c)2018-2028: chanpinxue.cn
 * Project: cts
 * Module Name: WebAPI
 * Comments: 请求接口
 * JDK version used: JDK1.8
 * Author: jzh
 * Create Date: 2018-11-05
 * Modified By: jzh
 * Modified Date: 2018-11-05
 * Why & What is modified:
 * Version: <1.0>
 */
public interface WebAPI {

    @GET("appApkVer.php")
    Call<ApkVer> getApkVer();
}

5、Test.java

package cn.mf.cts.retrofit;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * CopyRright (c)2018-2028: chanpinxue.cn
 * Project: cts
 * Module Name: Test
 * Comments: 测试
 * JDK version used: JDK1.8
 * Author: jzh
 * Create Date: 2018-11-05
 * Modified By: jzh
 * Modified Date: 2018-11-05
 * Why & What is modified:
 * Version: <1.0>
 */
public class Test {

    //
    public static void request() {

        // 创建Retrofit对象
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://chanpinxue.cn/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        // 创建网络请求接口的实例
        WebAPI request = retrofit.create(WebAPI.class);

        // 对发送请求进行封装
        Call<ApkVer> call = request.getApkVer();

        // 发送网络请求(异步)
        call.enqueue(new Callback<ApkVer>() {
            // 请求成功时候的回调
            @Override
            public void onResponse(Call<ApkVer> call, Response<ApkVer> response) {
                // 请求处理,输出结果
                response.body().show();
            }

            // 请求失败时候的回调
            @Override
            public void onFailure(Call<ApkVer> call, Throwable throwable) {
                System.out.println("连接失败");
            }
        });
    }
}

 

发表回复

您的电子邮箱地址不会被公开。