androidのretrofit2调用接口

简介: androidのretrofit2调用接口

所谓理解,通常不过是误解的总合。——村上春树《斯普特尼克恋人》

安卓调用接口

首先引入依赖

implementation 'com.android.volley:volley:1.1.1'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.3.0'

然后编写主配置类

package com.example.interfacecall.net;
import android.util.Log;
import com.android.volley.BuildConfig;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class NetConfig {
    /**
     * url
     */
    public final static String BASEURL = "http://vampireachao.utools.club/";
    private static Retrofit.Builder builder;
    private static Retrofit retrofit;
    public static Retrofit.Builder getRetrofitBuilder() {
        if (builder == null) {
            Gson gson = new GsonBuilder()
                    .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                    .setLenient()
                    .create();//使用 gson coverter,统一日期请求格式
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor(message -> Log.e("OkHttp", ": " + message));
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
            okHttpBuilder
                    .readTimeout(15000, TimeUnit.MILLISECONDS)
                    .connectTimeout(15000, TimeUnit.MILLISECONDS)
                    .writeTimeout(15000, TimeUnit.MILLISECONDS)
                    .retryOnConnectionFailure(true);
            if (BuildConfig.DEBUG) {
                okHttpBuilder.addInterceptor(logging);
            }
            OkHttpClient httpClient = okHttpBuilder.build();
            builder = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(httpClient)
                    .baseUrl(BASEURL);
        }
        return builder;
    }
    public static Retrofit getRetrofit() {
        if (retrofit == null) {
            retrofit = getRetrofitBuilder().build();
        }
        return retrofit;
    }
    public static <T> T create(Class<T> t) {
        return getRetrofit().create(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
package com.example.interfacecall.net;
import android.util.Log;
import com.google.gson.Gson;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
publicabstractclassCustomCallBack<T> implementsCallback<T> {
@Override
publicvoidonResponse(Call<T> call, Response<T> response) {
        Log.e("okhttp: content_result ", newGson().toJson(response.body()));
if (response.raw().code() == 500) {
            failure(newThrowable("500"));
return;
        }
if (response.body() == null) {
            failure(newThrowable("500"));
return;
        }
        response(response);
    }
@Override
publicvoidonFailure(Call<T> call, Throwable t) {
        t.printStackTrace();
        failure(t);
    }
publicabstractvoidresponse(Response<T> response);
publicabstractvoidfailure(Throwable t);
}

定义接口

package com.example.interfacecall.net;
import com.example.interfacecall.bean.User;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Path;
import retrofit2.http.Query;
public class ProjectApi {
    public interface UserProject {
        @GET("user/shout")
        Call<AjaxJson> shout();
        /**
         * user/say?word=
         * @param word
         * @return
         */
        @GET("user/say")
        Call<AjaxJson> say(@Query("word") String word);
        /**
         * user/say/xxx
         * @param word
         * @return
         */
        @GET("user/say/{word}")
        Call<AjaxJson> speak(@Path("word") String word);
        /**
         * requestBody里{username:"xxx",password:"xxx"}
         * @param user
         * @return
         */
        @POST("user/login")
        Call<AjaxJson> login(@Body User user);
    }
}

然后调用

package com.example.interfacecall;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.example.interfacecall.bean.User;
import com.example.interfacecall.net.AjaxJson;
import com.example.interfacecall.net.CustomCallBack;
import com.example.interfacecall.net.NetConfig;
import com.example.interfacecall.net.ProjectApi;
import com.example.interfacecall.utils.ToastUtils;
import java.util.Optional;
import retrofit2.Call;
import retrofit2.Response;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        say();
        speak();
//        login();
//        shout();
    }
    private void say() {
        findViewById(R.id.hello).setOnClickListener(v -> {
            Call<AjaxJson> shout = NetConfig.create(ProjectApi.UserProject.class).say("阿巴阿巴阿巴");
            shout.enqueue(new CustomCallBack<AjaxJson>() {
                @Override
                public void response(Response<AjaxJson> response) {
                    ToastUtils.showToast(getApplicationContext(), Optional.ofNullable(response.body()).orElse(new AjaxJson()).getData());
                }
                @Override
                public void failure(Throwable t) {
                    ToastUtils.showToast(getApplicationContext(), "网络异常");
                }
            });
        });
    }
    private void speak() {
        findViewById(R.id.hello).setOnClickListener(v -> {
            Call<AjaxJson> shout = NetConfig.create(ProjectApi.UserProject.class).speak("阿巴阿巴阿巴");
            shout.enqueue(new CustomCallBack<AjaxJson>() {
                @Override
                public void response(Response<AjaxJson> response) {
                    ToastUtils.showToast(getApplicationContext(), Optional.ofNullable(response.body()).orElse(new AjaxJson()).getData());
                }
                @Override
                public void failure(Throwable t) {
                    ToastUtils.showToast(getApplicationContext(), "网络异常");
                }
            });
        });
    }
    private void login() {
        findViewById(R.id.hello).setOnClickListener(v -> {
            User user = new User("rubenHappyAchao", "Ruben8848");
            Call<AjaxJson> shout = NetConfig.create(ProjectApi.UserProject.class).login(user);
            shout.enqueue(new CustomCallBack<AjaxJson>() {
                @Override
                public void response(Response<AjaxJson> response) {
                    ToastUtils.showToast(getApplicationContext(), Optional.ofNullable(response.body()).orElse(new AjaxJson()).getMsg());
                }
                @Override
                public void failure(Throwable t) {
                    ToastUtils.showToast(getApplicationContext(), "网络异常");
                }
            });
        });
    }
    private void shout() {
        findViewById(R.id.hello).setOnClickListener(v -> {
            Call<AjaxJson> shout = NetConfig.create(ProjectApi.UserProject.class).shout();
            shout.enqueue(new CustomCallBack<AjaxJson>() {
                @Override
                public void response(Response<AjaxJson> response) {
                    ToastUtils.showToast(getApplicationContext(), Optional.ofNullable(response.body()).orElse(new AjaxJson()).getMsg());
                }
                @Override
                public void failure(Throwable t) {
                    ToastUtils.showToast(getApplicationContext(), "网络异常");
                }
            });
        });
    }
}

完整安卓代码放到了gitee仓库里,感兴趣的可以自取。。。

接口后端代码

相关文章
|
3月前
|
Linux Android开发
Android 正常运行所需的一系列 Linux 内核接口
Android 正常运行所需的一系列 Linux 内核接口
53 0
|
4月前
|
XML JSON Java
Android App网络通信中通过okhttp调用HTTP接口讲解及实战(包括GET、表单格式POST、JSON格式POST 附源码)
Android App网络通信中通过okhttp调用HTTP接口讲解及实战(包括GET、表单格式POST、JSON格式POST 附源码)
173 0
|
4月前
|
XML Java API
Android App开发之创建JNI接口获取CPU指令集讲解及实战(附源码 简单易懂)
Android App开发之创建JNI接口获取CPU指令集讲解及实战(附源码 简单易懂)
42 0
|
4月前
|
XML Java 定位技术
Android Studio App开发之网络通信中使用GET方式调用HTTP接口的讲解及实战(附源码 超详细必看)
Android Studio App开发之网络通信中使用GET方式调用HTTP接口的讲解及实战(附源码 超详细必看)
58 0
|
5月前
|
IDE 网络安全 开发工具
安卓模拟器接口抓包教程
用uni-app开发安卓应用时,查看接口数据不能像在浏览器中可以直接通过network查看,只能借助抓包工具来抓包,还有一些线上应用我们也只能通过抓包来排查具体的问题
332 0
|
8月前
|
Java Android开发
Android 中通过Intent传递类对象,通过实现Serializable和Parcelable接口两种方式传递对象
Android 中通过Intent传递类对象,通过实现Serializable和Parcelable接口两种方式传递对象
77 1
|
10月前
|
Android开发 C++
Android系统的Ashmem匿名共享内存子系统分析(3)- Ashmem子系统的 C/C++访问接口
Android系统的Ashmem匿名共享内存子系统分析(3)- Ashmem子系统的 C/C++访问接口
126 0
|
11月前
|
XML 数据格式
Android_点击事件(实现接口OnClickListener)
关于每个Fragment里面都会有点击事件,如果一个Fragment里面很多控件有点击事件,那么就让这个Fragment类实现点击事件接口,例如
96 0
|
存储 数据库 数据安全/隐私保护
Android11.0(R) 预留清空锁屏密码接口
Android11.0(R) 预留清空锁屏密码接口
207 0
|
Java 数据库 Android开发
Android MTK平台 客制化系统来电界面(屏蔽 InCallUI 提供接口给客户自行展示来电去电页面)
Android MTK平台 客制化系统来电界面(屏蔽 InCallUI 提供接口给客户自行展示来电去电页面)
155 0