一、OkHttp的使用
依赖
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okio:okio:1.11.0'
混淆配置
# okhttp3
-dontwarn okhttp3.**
-dontwarn okio.**
-dontwarn javax.annotation.**
# A resource is loaded with a relative path so the package of this class must be preserved.
-keepnames class okhttp3.internal.publicsuffix.PublicSuffixDatabase
二、Get请求方式
//性能优化,每次网络请求都创建会造成资源浪费
private static final OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.retryOnConnectionFailure(false) -> 超时不需要重连
.build();
public static void sendOkHttpClient(String url, LinkedHashMap<String, String> map, final onResultListener listener) {
Request request = new Request.Builder()
.url(attachHttpGetParams(url, map))
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
response.close(); //资源回收
}
});
}
private static String attachHttpGetParams(String url, LinkedHashMap<String, String> map) {
Iterator<String> keys = map.keySet().iterator();
Iterator<String> values = map.values().iterator();
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("?");
for (int i = 0; i < map.size(); i++) {
String value = null;
try {
value = URLEncoder.encode(values.next(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
stringBuffer.append(keys.next() + "=" + value);
if (i != map.size() - 1) {
stringBuffer.append("&");
}
}
return url + stringBuffer.toString();
}
三、Post请求方式
提交FormBody
public static void sendOkHttpClient(String url, Map<String, String> map, final onResultListener listener) {
FormBody.Builder builder = new FormBody.Builder();
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
builder.add(entry.getKey(), entry.getValue());
}
Request request = new Request
.Builder()
.post(builder.build())
.url(url)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
response.close(); //资源回收
}
});
}
提交MultipartBody
public static void YXCreateAccount(String accid, String name, String token, String url, Callback callback) {
String appKey = "appKey";
String appSecret = "appSecret";
String nonce = "12345";
String curTime = String.valueOf((new Date()).getTime() / 1000L);
String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
Map<String, String> map = new HashMap<>();
map.put("accid", accid);
map.put("name", name);
map.put("token", token);
//遍历map请求参数
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
builder.addFormDataPart(entry.getKey(), entry.getValue());
}
final Request request = new Request.Builder()
.addHeader("AppKey", appKey)
.addHeader("Nonce", nonce)
.addHeader("CurTime", curTime)
.addHeader("CheckSum", checkSum)
.addHeader("Content-Type",
"application/x-www-form-urlencoded;charset=utf-8")
.url(url).post(builder.build()).build();
OkHttpClient client = new OkHttpClient();
client.newCall(request).enqueue(callback);
}
四、Retrofit的使用
依赖(适配Rxjava和Gson)
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
混淆配置
# Retain generic type information for use by reflection by converters and adapters.
-keepattributes Signature
# Retain service method parameters.
-keepclassmembernames,allowobfuscation interface * {
@retrofit2.http.* <methods>;
}
# Ignore annotation used for build tooling.
-dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement
创建Retrofit工具类
import java.util.HashMap;
import java.util.Map;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.HTTP;
import retrofit2.http.Path;
public class RetrofitUtil {
private static final String sUrl="http://192.168.43.45:8080/developer/api/";
private static Retrofit sRetrofit = new Retrofit.Builder()
.baseUrl(sUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
private static RetrofitService sRetrofitService = sRetrofit.create(RetrofitService.class);
public static void getInfo(int id,Callback<ResponseBody> callback){
sRetrofitService.getId(id).enqueue(callback);
}
public static Retrofit getRetrofit(){
return sRetrofit;
}
public static RetrofitService getRetrofitService(){
return sRetrofitService;
}
}
创建Retrofit动态代理对象接口
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.HTTP;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.PartMap;
import retrofit2.http.Path;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
public interface RetrofitService {
@GET("developers") -> 以sUrl/developers为例
Call<ResponseBody> getId();
@GET("{developers}") -> 以 sUrl/ "str" 为例
Call<ResponseBody> getId(@Path("developers")String str);
@GET("developers") -> 以sUrl/developers?id=ids为例
Call<ResponseBody> getId(@Query("id") int id);
@GET("developers") -> 以sUrl/developers?id=ids为例
Call<ResponseBody> getId(@QueryMap Map<String, Integer> map);
@GET -> 以url=sUrl/developers||url=developers为例
Call<ResponseBody> getId(@Url String url);
@POST("developers") -> 以sUrl/developers?id=ids为例
@FormUrlEncoded -> 以表单形式提交
Call<ResponseBody> getId(@Field("id") int id);
@POST("developers") -> 以sUrl/developers?id=ids为例
@FormUrlEncoded -> 以表单形式提交
Call<ResponseBody> getId(@FieldMap Map<String,Integer> map);
@POST("developers") -> 以sUrl/developers?id=ids为例
@Multipart -> 以文件形式提交
Call<ResponseBody> getId(@Part("id") int id);
@POST("developers") -> 以sUrl/developers?id=ids为例
@Multipart -> 以文件形式提交
Call<ResponseBody> getId(@PartMap Map<String,Integer> map);
@POST("developes") -> 以sUrl/developers?id=ids为例
@Header("name:wjx") -> 添加单个请求头
@Headers("name:wjx","pass:xjw") -> 添加多个请求头
Call<ResponseBody> getId(@Body User user); -> 添加请求体
@HTTP(method="GET",path="developers",hasBody=false) ->方法类型要全大写
Call<ResponseBody> getId();
}
使用Retrofit访问接口内容
RetrofitUtil.getInfo(id, new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
Retrofit接口注解详解
1、@GET("url匹配路径"),标注请求为Get方式
2、@POST("url匹配路径"),标注请求为POST方式
3、@HTTP(method = "GET",path = "url匹配路径",hasBody = false"),配置请求方式,配置请求路径,配置是否有请求体
4、@Path("replace"),替代Url {replace} 中的字段
5、@Query("id") && @QueryMap,配置Get请求方式的传参
6、@Url,被注解标识的传参,作为Retrofit的请求路径
7、@FormUrlEncoded,配置表单提交方式的Post请求
8、@Field("id") && @FieldMap,配置表单提交方式的传参
9、@Multipart,配置文件提交方式的Post请求
10、@Part("id")&& @PartMap,配置文件提交方式的传参
11、@Header("name:wjx"),传递单个请求头
12、@Headers("name:wjx","pass:wjx"),传递多个请求头,以","分隔开
13、@Body,传递