本篇只展示更新的代码,没有变化的就不贴了。 上一篇 :Android 封装okhttp3网络请求
更新内容:
JsonParse
public class JsonParse {
private Object responseBodyResult;
public Object getResponseBodyResult() {
return responseBodyResult;
}
public String toGetJson(RequestEntity requestEntity) {
StringBuilder params = new StringBuilder("?");
try {
Class cls = requestEntity.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
params.append(field.getName());
params.append("=");
params.append(field.get(requestEntity));
params.append("&");
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return params.substring(0, params.length() - 1);
}
public String toPostJson(RequestEntity requestEntity) {
return new FilterGson().toJson(requestEntity);
}
public FormBody toFormBody(RequestEntity requestEntity) {
FormBody.Builder build = new FormBody.Builder();
try {
Class cls = requestEntity.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
field.get(requestEntity);
build.add(field.getName(), String.valueOf(field.get(requestEntity)));
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return build.build();
}
public RequestBody toRequestBody(String name, String sFile) {
MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
RequestBody requestBody = RequestBody.Companion.create(new File(sFile), mediaType);
return new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", name, requestBody)
.build();
}
public RequestBody toRequestBody(List<String> names, List<String> sFiles) {
MediaType mediaType = MediaType.parse("multipart/form-data; charset=utf-8");
if (names.size() == sFiles.size()) {
MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
for (int i = 0; i < sFiles.size(); i++) {
RequestBody requestBody = RequestBody.Companion.create(new File(sFiles.get(i)), mediaType);
builder.addFormDataPart("files", names.get(i), requestBody);
}
return builder.build();
}
return null;
}
public void parseJson(String json, Type type) {
try {
JSONObject jsonObject = new JSONObject(json);
String jsonBody = jsonObject.get("data").toString();
if (NetConstant.NULL.equals(jsonBody) || NetConstant.NULL_SLASH.equals(jsonBody)) {
try {
jsonBody = "{}";
responseBodyResult = new FilterGson().fromJson(jsonBody, type);
} catch (Exception e) {
jsonBody = "[]";
responseBodyResult = new FilterGson().fromJson(jsonBody, type);
}
} else {
responseBodyResult = new FilterGson().fromJson(jsonBody, type);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
HttpManager
public class HttpManager {
public static void init(String ip, String post) {
baseIp = ip;
basePort = post;
}
private static String baseIp;
private static String basePort;
private static String getRequestUrl(String action) {
String baseUrl = "http://%s:%s/offline/%s/";
return String.format(baseUrl, baseIp, basePort, action);
}
public static void getAsyn(String url, OkHttpManager.BaseCallback callback) {
OkHttpManager.getInstance().getAsyn(url, callback);
}
public static void getAsyn(RequestEntity requestEntity, OkHttpManager.BaseCallback callback) {
OkHttpManager.getInstance().getAsyn(getRequestUrl(requestEntity.getUrlName()) + new JsonParse().toGetJson(requestEntity), callback);
}
public static void postAsyn(RequestEntity requestEntity, OkHttpManager.BaseCallback callback) {
OkHttpManager.getInstance().postAsyn(getRequestUrl(requestEntity.getUrlName()), new JsonParse().toPostJson(requestEntity), callback);
}
public static void formBodyAsyn(RequestEntity requestEntity, OkHttpManager.BaseCallback callback) {
OkHttpManager.getInstance().postAsyn(getRequestUrl(requestEntity.getUrlName()), new JsonParse().toFormBody(requestEntity), callback);
}
public static void uploadAsyn(String url, String name, String file, OkHttpManager.BaseCallback callback) {
OkHttpManager.getInstance().uploadAsyn(url, new JsonParse().toRequestBody(name, file), callback);
}
public static void uploadAsyn(String url, List<String> names, List<String> sFiles, OkHttpManager.BaseCallback callback) {
OkHttpManager.getInstance().uploadAsyn(url, new JsonParse().toRequestBody(names, sFiles), callback);
}
public static void downloadAsyn(String url, String filePath, OkHttpManager.BaseCallback callback) {
OkHttpManager.getInstance().downloadAsyn(url, filePath, callback);
}
}
OkHttpManager
public class OkHttpManager {
private final Handler mHandler;
private final OkHttpClient okHttpClient;
private OkHttpManager() {
okHttpClient = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.connectTimeout(10, TimeUnit.SECONDS)
.build();
mHandler = new Handler(Looper.getMainLooper());
}
public static OkHttpManager getInstance() {
return OkHttpHolder.okHttpManager;
}
private static class OkHttpHolder {
private static OkHttpManager okHttpManager = new OkHttpManager();
}
public void getAsyn(String url, final BaseCallback callback) {
final Request request = new Request.Builder()
.url(url)
.get()
.build();
send(request, callback);
}
public void postAsyn(String url, String requestBody, final BaseCallback callback) {
MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
Request request = new Request.Builder()
.url(url)
.post(RequestBody.Companion.create(requestBody, mediaType))
.build();
send(request, callback);
}
public void postAsyn(String url, FormBody body, BaseCallback callback) {
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
send(request, callback);
}
public void uploadAsyn(String url, RequestBody body, BaseCallback callback) {
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
send(request, callback);
}
public void downloadAsyn(String url, String filePath, BaseCallback callback) {
Request request = new Request.Builder().url(url).build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
sendFailCallback(callback, call.toString());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) {
if (response.isSuccessful()) {
ResponseBody body = response.body();
if (body != null) {
writeFile(body,filePath);
}
}
}
});
}
private void send(Request request, final BaseCallback callback) {
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
sendFailCallback(callback, call.toString());
}
@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
if (HttpCode.CODE_200 == response.code()) {
JsonParse jsonParse = new JsonParse();
jsonParse.parseJson(response.body().string(), callback.mType);
sendSuccessCallBack(callback, jsonParse.getResponseBodyResult());
} else {
sendFailCallback(callback, HttpCode.CODE_9999_MSG);
}
}
});
}
private void writeFile(ResponseBody body, String filePath) {
InputStream is;
FileOutputStream fos = null;
is = body.byteStream();
File file = new File(filePath);
try {
fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void sendSuccessCallBack(final BaseCallback callback, final Object responseBody) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onSuccess(responseBody);
}
}
});
}
private void sendFailCallback(final BaseCallback callback, final String msg) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (null != callback) {
callback.onFailure(msg);
}
}
});
}
public static abstract class BaseCallback<T> {
Type mType;
public BaseCallback() {
mType = getSuperclassTypeParameter(getClass());
}
static Type getSuperclassTypeParameter(Class<?> subclass) {
Type superclass = subclass.getGenericSuperclass();
if (superclass instanceof Class) {
throw new RuntimeException("Enter generics in BaseResultCallback");
}
ParameterizedType parameterized = (ParameterizedType) superclass;
return parameterized.getActualTypeArguments()[0];
}
public abstract void onFailure(String message);
public abstract void onSuccess(T result);
}
}
|