使用实例(以post 带请求头 请求参数为例)
String headerKey = "token,type";
String token= "";
String type = "";
String parameterKey = "";
RetrofitUtils.getHttpUtils("主路径")
.isOpenLog(true)//是否打开log
.setClassName("名称标识")//主要判断从那个类调用此方法
.doPost("绝对路径"
//请求头集合
, RetrofitUtils.header(headerKey, token,type)
//也可以手动new HashMap
//请求参数集合 同上
, RetrofitUtils.parameter(parameterKey,value1,value2)
, new RetrofitUtils.CallBack<"返回值对应的实体类">() {
@Override
public void onSuccess("返回值对应的实体类" bean) {
Log.d(TAG, "onSuccess: " + bean.toString());
}
}
@Override
public void onError(String error) {
Log.d(TAG, "onError: " + error);
}
});
全部源码
import android.util.Log;
import com.google.gson.Gson;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.http.FieldMap;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.HeaderMap;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.QueryMap;
import retrofit2.http.Url;
//使用前 需要导入依赖
/*
//retrofit
implementation 'com.squareup.retrofit2:retrofit:2.6.0'
//Gson converter
implementation 'com.squareup.retrofit2:converter-gson:2.6.0'
//RxJava2 Adapter
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.6.0'
//RxJava
implementation 'io.reactivex.rxjava2:rxjava:2.2.7'
implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
*/
public class RetrofitUtils {
private static RetrofitUtils httpUtils = null;//单例获取对象
private final API API;
private final String TAG = RetrofitUtils.class.getName();
private static Gson gson = new Gson();
private static HashMap<String, Object> stringStringHashMap = new HashMap<>();
private boolean isOpenLog = false;//是否打开log
private String classname = "";
private final MultipartBody.Builder builder;
//初始化
private RetrofitUtils(String url) {
OkHttpClient build = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor())
.connectTimeout(1000 * 30, TimeUnit.MILLISECONDS)
.writeTimeout(1000 * 30, TimeUnit.MILLISECONDS)
.build();
API = new Retrofit.Builder()
.baseUrl(url)
.client(build)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build().create(API.class);
builder = new MultipartBody.Builder();
}
//单例获取对象
public static RetrofitUtils getHttpUtils(String url) {
if (httpUtils == null) {
synchronized (RetrofitUtils.class) {
if (httpUtils == null) {
httpUtils = new RetrofitUtils(url);
}
}
}
return httpUtils;
}
//get请求有参
public <T> RetrofitUtils doGet(String url, Map<String, Object> map, final CallBack<T> callBack) {
API.doGet(url, map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
if (isOpenLog) {
Log.e(TAG, "onNext: " + classname + "\n" + string);
}
Type[] genericInterfaces = callBack.getClass().getGenericInterfaces();
Type[] actualTypeArguments = ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments();
Type actualTypeArgument = actualTypeArguments[0];
T o = gson.fromJson(string, actualTypeArgument);
callBack.onSuccess(o);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
callBack.onError(e.toString());
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
//get请求请求头 有参
public <T> RetrofitUtils doGet(String url, Map<String, Object> header, Map<String, Object> map, final CallBack<T> callBack) {
API.doGet(url, header, map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
if (isOpenLog) {
Log.e(TAG, "onNext: " + classname + "\n" + string);
}
Type[] genericInterfaces = callBack.getClass().getGenericInterfaces();
Type[] actualTypeArguments = ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments();
Type actualTypeArgument = actualTypeArguments[0];
T o = gson.fromJson(string, actualTypeArgument);
callBack.onSuccess(o);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
callBack.onError(e.toString());
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
//get请求 返回值是集合
public <T> RetrofitUtils doGetArray(String url, final ArrayCallBack callBack) {
API.doGetArray(url)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
if (isOpenLog) {
Log.e(TAG, "onNext: " + classname + "\n" + string);
}
callBack.onSuccess(string);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
callBack.onError(e.toString());
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
//get请求 无参
public <T> RetrofitUtils doGet(String url, final CallBack<T> callBack) {
API.doGet(url)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
if (isOpenLog) {
Log.e(TAG, "onNext: " + classname + "\n" + string);
}
Type[] genericInterfaces = callBack.getClass().getGenericInterfaces();
Type[] actualTypeArguments = ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments();
Type actualTypeArgument = actualTypeArguments[0];
T o = gson.fromJson(string, actualTypeArgument);
callBack.onSuccess(o);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
callBack.onError(e.toString());
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
//post请求 有参
public <T> RetrofitUtils doPost(String url, Map<String, Object> map, final CallBack<T> callBack) {
API.doPost(url, map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
if (isOpenLog) {
Log.e(TAG, "onNext: " + classname + "\n" + string);
}
Type[] genericInterfaces = callBack.getClass().getGenericInterfaces();
Type[] actualTypeArguments = ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments();
Type actualTypeArgument = actualTypeArguments[0];
T o = gson.fromJson(string, actualTypeArgument);
callBack.onSuccess(o);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
callBack.onError(e.toString());
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
//post请求 请求头 有参
public <T> RetrofitUtils doPost(String url, Map<String, Object> header, Map<String, Object> map, final CallBack<T> callBack) {
API.doPost(url, header, map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
if (isOpenLog) {
Log.e(TAG, "onNext: " + classname + "\n" + string);
}
Type[] genericInterfaces = callBack.getClass().getGenericInterfaces();
Type[] actualTypeArguments = ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments();
Type actualTypeArgument = actualTypeArguments[0];
T o = gson.fromJson(string, actualTypeArgument);
callBack.onSuccess(o);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
callBack.onError(e.toString());
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
//上传图片
public <T> RetrofitUtils doFile(String url, File file, CallBack<T> callBack) {
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);//上传的文件
List<MultipartBody.Part> parts = builder.setType(MultipartBody.FORM)
//在这里添加服务器除了文件之外的其他参数
.addFormDataPart("file", file.getName(), body).build().parts();
final Observable<ResponseBody> upload = API.upload(url, parts);
upload.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
if (isOpenLog) {
Log.e(TAG, "onNext: " + classname + "\n" + string);
}
Type[] genericInterfaces = callBack.getClass().getGenericInterfaces();
Type[] actualTypeArguments = ((ParameterizedType) genericInterfaces[0]).getActualTypeArguments();
Type actualTypeArgument = actualTypeArguments[0];
T o = gson.fromJson(string, actualTypeArgument);
callBack.onSuccess(o);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
//上传图片 请求头
public <T> RetrofitUtils doFile(String url, Map<String, Object> header, File file, CallBack<T> callBack) {
RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);//上传的文件
List<MultipartBody.Part> parts = builder.setType(MultipartBody.FORM)
//在这里添加服务器除了文件之外的其他参数
.addFormDataPart("file", file.getName(), body).build().parts();
final Observable<ResponseBody> upload = API.upload(url, header, parts);
upload.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
try {
String string = responseBody.string();
if (isOpenLog) {
Log.e(TAG, "onNext: " + classname + "\n" + string);
}
Type[] genericInterfaces = callBack.getClass().getGenericInterfaces();
Type[] actualTypeArguments = ((ParameterizedType)
genericInterfaces[0]).getActualTypeArguments();
Type actualTypeArgument = actualTypeArguments[0];
T o = gson.fromJson(string, actualTypeArgument);
callBack.onSuccess(o);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
//post请求 请求头 有参
@SuppressLint("NewApi")
public RetrofitUtils doPostString(String url, Map<String, Object> header, Map<String, Object> map, final CallBack<String> callBack) {
API.doPost(url, header, map)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<ResponseBody>() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onNext(ResponseBody responseBody) {
String string = null;
try {
string = responseBody.string();
callBack.onSuccess(string);
} catch (IOException e) {
Log.e(TAG, "onNext: " + classname + "\n" + e.toString() + "\n" + string);
e.printStackTrace();
}
}
@Override
public void onError(Throwable e) {
callBack.onError(e.toString());
}
@Override
public void onComplete() {
}
});
return httpUtils;
}
interface API {
@POST
@FormUrlEncoded
Observable<ResponseBody> doPost(@Url String url, @FieldMap Map<String, Object> map);
@GET
Observable<ResponseBody> doGet(@Url String url, @QueryMap Map<String, Object> map);
@GET
Observable<ResponseBody> doGet(@Url String url);
@GET
Observable<ResponseBody> doGetArray(@Url String url);
@POST
@FormUrlEncoded
Observable<ResponseBody> doPost(@Url String url, @HeaderMap Map<String, Object> headerMap, @FieldMap Map<String, Object> map);
@GET
Observable<ResponseBody> doGet(@Url String url, @HeaderMap Map<String, Object> headerMap, @QueryMap Map<String, Object> map);
@Multipart
@POST
Observable<ResponseBody> upload(@Url String url, @Part List<MultipartBody.Part> partList);
@Multipart
@POST
Observable<ResponseBody> upload(@Url String url, @HeaderMap Map<String, Object> headerMap, @Part List<MultipartBody.Part> partList);
}
public RetrofitUtils setClassName(String name) {
this.classname = name;
return httpUtils;
}
public RetrofitUtils isOpenLog(boolean isOpenLog) {
this.isOpenLog = isOpenLog;
return httpUtils;
}
//请求头集合 key通过“,”拼接 如果是String以外的数据类型 需要手动添加对应方法 或者进行转换
public static HashMap<String, Object> header(String appid, String version) {
stringStringHashMap.put("appid", appid);
stringStringHashMap.put("version", version);
return stringStringHashMap;
}
public static HashMap<String, Object> header(String key, String... parameter) {
String[] split = key.split(",");
for (int i = 0; i < split.length; i++) {
stringStringHashMap.put(split[i], parameter[i]);
}
return stringStringHashMap;
}
//参数集合 key通过“,”拼接 如果是String以外的数据类型 需要手动添加对应方法 或者进行转换
public static HashMap<String, Object> parameter(String key, String... parameter) {
String[] split = key.split(",");
for (int i = 0; i < split.length; i++) {
stringStringHashMap.put(split[i], parameter[i]);
}
return stringStringHashMap;
}
//参数集合 手动添加
public static HashMap<String, Object> parameter() {
return stringStringHashMap;
}
//数据返回回调方法
public interface CallBack<T> {
void onSuccess(T bean);
void onError(String error);
}
//返回数据是数组,回调方法
interface ArrayCallBack {
void onSuccess(String responseBody);
void onError(String error);
}
//拦截器
class LoggingInterceptor implements Interceptor {
private static final String TAG = "LoggingInterceptor";
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();//获取请求数据
//1.请求前--打印请求信息
long startTime = System.nanoTime();
Log.d(TAG, String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
//2.网络请求
Response response = chain.proceed(request);
//3.网络响应后--打印响应信息
long endTime = System.nanoTime();
Log.d(TAG, String.format("Received response for %s in %.1fms%n%s", response.request().url(), (endTime - startTime) / 1e6d, response.headers()));
return response;
}
}
}