网络通信用的就是okhttp,这一篇就不详细介绍了,主要分享一下封装好的工具类。
用到的依赖库:
//网络框架
implementation 'com.squareup.okhttp3:okhttp:4.6.0'
//网络请求封装框架
implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.6.2'
public class RetrofitUtil {
private Retrofit sRetrofit;
private RetrofitUtil() {
sRetrofit = initRetrofit();
}
private static class Inner {
private static final RetrofitUtil INSTANCE = new RetrofitUtil();
}
/**
* 获取 静态内部类单例
* @return 静态内部类单例
*/
public static RetrofitUtil getInstance() {
return Inner.INSTANCE;
}
/**
* 创建 Retrofit 实例
* @return Retrofit实例
*/
private Retrofit initRetrofit() {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
.readTimeout(10, TimeUnit.SECONDS) //传输超时时间
.connectTimeout(10, TimeUnit.SECONDS) //连接超时时间
//网络数据查看拦截器
.addInterceptor(new CustomInterceptor());
final Gson gson = new GsonBuilder()
.disableHtmlEscaping() //禁止转码
.setLenient() //允许超长字符串
.create();
return new Retrofit.Builder()
.baseUrl(“这里填服务器地址(http://www.xxx.com/)”) //服务器地址
.client(builder.build())
.addConverterFactory(CustomGsonConverterFactory.create(gson))//解析的封装类
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使用注解方式把请求定义成接口
.build();
}
/**
* 创建 Api 请求类
* @param api Api请求原始反射类
* @param <T> 泛型
* @return Api请求类
*/
public <T> T create(final Class<T> api) {
return sRetrofit.create(api);
}
}
CustomInterceptor网络拦截器我要额外说一下,当时的网络拦截器会主动请求服务器两次,当时让我找了好久才找到位置改好,下面是改好后的。
public class CustomInterceptor implements Interceptor {
@NotNull
@Override
public Response intercept(@NotNull Chain chain) throws IOException {
Request request = chain.request();
RequestBody requestBody = request.body();
if (requestBody instanceof FormBody) {
//表单请求
FormBody formBody = (FormBody) requestBody;
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < formBody.size(); ++i) {
String encodeName = formBody.encodedName(i);
String encodeValue = formBody.encodedValue(i);
String name = formBody.name(i);
String value = formBody.value(i);
strBuilder.append(name + "=" + value + "\n");
// strBuilder.append(" encodeName: " + encodeName + " encodeValue: " + encodeValue + " name: " + name + " value: " + value);
}
System.out.println("请求头: " + formBody.contentType());
System.out.println("请求体: " + strBuilder.toString());
System.out.println("url:" + request.url());
} else if (requestBody instanceof MultipartBody) {
//文件上传请求
MultipartBody multipartBody = (MultipartBody) requestBody;
}
Response response = chain.proceed(request);
ResponseBody responseBody = response.body();
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.getBuffer();
Charset UTF8 = Charset.forName("UTF-8");
System.out.println("返回数据: " + buffer.clone().readString(UTF8));
return response;
}
}
使用方法:
public class BaseBean<T> {
@SerializedName("code")
public int code;
@SerializedName("msg")
public String msg;
@SerializedName("data")
public T data;
public T getData() {
return CastUtil.cast(data);
}
}
public class LoginBean {
@SerializedName("id")
public String id;
@SerializedName("username")
public String username;
@SerializedName("password")
public String password;
}
/**
* 网络请求接口
*
* @param postMap 数据
* @return Single
*/
@FormUrlEncoded
@POST("这里填接口地址(index/index/login)")
Single<这里填bean类(BaseBean<LoginBean>)> login(@FieldMap Map<String, Object> postMap);
RetrofitUtil.getInstance()
.create(ServerApi.class)
.login(postMap)//Map参数集合
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((BaseBean<LoginBean> bean) -> {
}, (Throwable throwable) -> {
throwable.printStackTrace();
});
网友评论