参考文章:https://blog.csdn.net/tantion/article/details/81112039
- 导入包
compileOnly 'com.squareup.okhttp3:okhttp:4.2.1'
compileOnly 'com.squareup.okhttp3:logging-interceptor:4.2.1'
compileOnly 'com.google.code.gson:gson:2.8.5'
compileOnly 'com.squareup.retrofit2:retrofit:2.6.2'
compileOnly 'com.squareup.retrofit2:converter-gson:2.6.2'
‘com.squareup.okhttp3:logging-interceptor:4.2.1’ — 搭配日志使用
‘com.squareup.retrofit2:converter-gson:2.6.2’ — Json解析
- AndroidManifest.xml 加入网络权限
<uses-permission android:name="android.permission.INTERNET" />
- 创建数据访问接口
public interface Request_Interface {
// @POST注解的作用:采用Post方法发送网络请求
// getLoginInfo() = 接收网络请求数据的方法
// @Body BaseReq<LoginRequest> loginReq --- 输入参数,根据各自的输入参数设置
// 其中返回类型为Call<*>,*是接收数据的类(ResponseBody是直接返回json字符串)
@POST("咱们网络接口")
Call<ResponseBody> getLoginInfo(@Body BaseReq<LoginRequest> loginReq);
}
- 创建 Retrofit 对象
Retrofit retrofit = new Retrofit.Builder()
.client(okHttpBuilder.build())
//设置网络请求的Url地址
.baseUrl("咱们的网络请求")
//设置数据解析器
.addConverterFactory(GsonConverterFactory.create())
.build();
- okhttp设置日志拦截器
该步骤,根据自身需求设置。设置的好处是,可以看到使用okhttp请求接口日志。建议设置,因为可以设置BuildConfig.DEBUG,正式打包的时候,日志不会打印。
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) { // 为了正式打包的时候,不打印日志
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
okHttpBuilder.addInterceptor(loggingInterceptor);
}
- 使用实例
Request_Interface service = retrofit.create(Request_Interface.class);
BaseReq<LoginRequest> loginReq = new BaseReq<>();
LoginRequest loginReqData = new LoginRequest();
loginReqData.userCode = "";
loginReqData.userPwd = "";
loginReq.data = loginReqData;
Call<ResponseBody> call1 = service.getLoginInfo(loginReq);
call1.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
// 打印Json数据
L.e("xiaozhen", "body = " + response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
t.printStackTrace();
}
});
跟着步骤来写,简单使用没问题。
总结:
- 批量使用,需要斟酌。如果需要批量使用,将Retrofit和okhttp封装,便于使用。
- 还可以结合Rxjava使用,链表形式,代码结构更容易查看。
- 多练习,Post只是它们强大功能的一小小小部分。
本文介绍了如何在Android中使用Retrofit2和okhttp3进行POST请求,包括导入相关依赖、添加网络权限、定义接口、创建Retrofit实例以及设置日志拦截器。文中提供了一个简单的使用示例,并指出在批量使用时可以考虑封装Retrofit和okhttp,以提高代码复用性和可读性。同时提到,结合Rxjava可以进一步优化代码结构。

1887

被折叠的 条评论
为什么被折叠?



