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仓库里,感兴趣的可以自取。。。

接口后端代码

相关文章
|
Android开发
Android MediaTek 平台增加UART接口的红外模块支持,支持NEC红外遥控
Android MediaTek 平台增加UART接口的红外模块支持,支持NEC红外遥控
604 0
|
Linux Android开发
Android 正常运行所需的一系列 Linux 内核接口
Android 正常运行所需的一系列 Linux 内核接口
363 0
|
XML JSON Java
Android App网络通信中通过okhttp调用HTTP接口讲解及实战(包括GET、表单格式POST、JSON格式POST 附源码)
Android App网络通信中通过okhttp调用HTTP接口讲解及实战(包括GET、表单格式POST、JSON格式POST 附源码)
2689 0
|
JSON Java API
【Android】使用 Retrofit2 发送异步网络请求的简单案例
**摘要:** Retrofit是Android和Java的HTTP客户端库,简化了RESTful API交互。它通过Java接口定义HTTP请求,并提供注解管理参数、HTTP方法等。要使用Retrofit,首先在AndroidManifest.xml中添加`INTERNET`权限,然后在`build.gradle`中引入Retrofit和Gson依赖。创建服务器响应数据类和描述接口的接口,如`Result`和`Api`。通过Retrofit.Builder配置基础URL并构建实例,之后调用接口方法创建Call对象并发送异步请求。
837 1
|
Java 开发工具 Android开发
如何访问 android系统hide的类或接口
如何访问 android系统hide的类或接口
1179 1
|
Android开发 开发者
Android项目架构设计问题之使用动态代理来增强 GoodsApi 接口的调用如何解决
Android项目架构设计问题之使用动态代理来增强 GoodsApi 接口的调用如何解决
312 0
|
存储 缓存 Java
Android项目架构设计问题之优化业务接口数据的加载效率如何解决
Android项目架构设计问题之优化业务接口数据的加载效率如何解决
301 0
|
Java Android开发 开发者
Android项目架构设计问题之使用Retrofit2作为网络库如何解决
Android项目架构设计问题之使用Retrofit2作为网络库如何解决
381 0
|
XML 网络协议 Java
53. 【Android教程】Socket 网络接口
53. 【Android教程】Socket 网络接口
808 0

热门文章

最新文章