網(wǎng)絡(luò)通信用的就是okhttp,這一篇就不詳細(xì)介紹了弟胀,主要分享一下封裝好的工具類。
用到的依賴庫:
//網(wǎng)絡(luò)框架
implementation 'com.squareup.okhttp3:okhttp:4.6.0'
//網(wǎng)絡(luò)請求封裝框架
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();
}
/**
* 獲取 靜態(tài)內(nèi)部類單例
* @return 靜態(tài)內(nèi)部類單例
*/
public static RetrofitUtil getInstance() {
return Inner.INSTANCE;
}
/**
* 創(chuàng)建 Retrofit 實(shí)例
* @return Retrofit實(shí)例
*/
private Retrofit initRetrofit() {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder()
.readTimeout(10, TimeUnit.SECONDS) //傳輸超時時間
.connectTimeout(10, TimeUnit.SECONDS) //連接超時時間
//網(wǎng)絡(luò)數(shù)據(jù)查看攔截器
.addInterceptor(new CustomInterceptor());
final Gson gson = new GsonBuilder()
.disableHtmlEscaping() //禁止轉(zhuǎn)碼
.setLenient() //允許超長字符串
.create();
return new Retrofit.Builder()
.baseUrl(“這里填服務(wù)器地址(http://www.xxx.com/)”) //服務(wù)器地址
.client(builder.build())
.addConverterFactory(CustomGsonConverterFactory.create(gson))//解析的封裝類
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//使用注解方式把請求定義成接口
.build();
}
/**
* 創(chuàng)建 Api 請求類
* @param api Api請求原始反射類
* @param <T> 泛型
* @return Api請求類
*/
public <T> T create(final Class<T> api) {
return sRetrofit.create(api);
}
}
CustomInterceptor網(wǎng)絡(luò)攔截器我要額外說一下咖楣,當(dāng)時的網(wǎng)絡(luò)攔截器會主動請求服務(wù)器兩次,當(dāng)時讓我找了好久才找到位置改好,下面是改好后的。
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("返回?cái)?shù)據(jù): " + 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;
}
/**
* 網(wǎng)絡(luò)請求接口
*
* @param postMap 數(shù)據(jù)
* @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參數(shù)集合
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe((BaseBean<LoginBean> bean) -> {
}, (Throwable throwable) -> {
throwable.printStackTrace();
});