欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

基于okhttp的文件和json混合上传

程序员文章站 2022-04-29 13:41:57
...
public class UploadHelper {
/**
 * 该方法返回observable对象,可以直接进行观察;返回的方法均是ui线程
 *
 * [@param](https://my.oschina.net/u/2303379) requestUrl 接口名称,如果服务域名也不一致,要拼出全路径
 * [@param](https://my.oschina.net/u/2303379) fileMap    文件map,key一定与后台字段对应
 * [@param](https://my.oschina.net/u/2303379) dataMap    基于业务场景,新增参数
 * [@param](https://my.oschina.net/u/2303379) listener   接口请求回调
 */
public static Observable<String> upload([@NonNull](https://my.oschina.net/u/2981441) final String requestUrl, @NonNull final Map<String, String> fileMap, final Map<String, String> dataMap) {
    return Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(final Subscriber<? super String> subscriber) {
            upload(requestUrl, fileMap, dataMap, new UploadListener() {
                @Override
                public void onResult(String jsonResult) {
                    subscriber.onNext(jsonResult);
                }

                @Override
                public void onFailed(String errorMsg) {
                    subscriber.onError(new Throwable(errorMsg));
                }
            });
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}


/**
 * 该方法回调再子线程,如果需要操作ui,需要手动切换ui线程
 *
 * @param requestUrl 接口名称,如果服务域名也不一致,要拼出全路径
 * @param fileMap    文件map,key一定与后台字段对应
 * @param dataMap    基于业务场景,新增参数
 * @param listener   接口请求回调
 */
public static void upload(@NonNull String requestUrl, @NonNull Map<String, String> fileMap, Map<String, String> dataMap, final UploadListener listener) {
    MultipartBody.Builder requestBuilder = new MultipartBody.Builder();
    if (fileMap != null && fileMap.size() >= 1) {
        for (Map.Entry entry : fileMap.entrySet()) {
            requestBuilder.addFormDataPart(valueOf(entry.getKey()), UUID.randomUUID() + "", RequestBody.create(MediaType.parse("application/octet-stream"), new File(valueOf(entry.getValue()))));
        }
    }
    HashMap<String, String> data = new HashMap<>();
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.excludeFieldsWithoutExposeAnnotation();
    final Gson gson = gsonBuilder.create();
    data.put("header", gson.toJson(getRequestJsonHeader()));
    if (dataMap != null) {
        data.put("data", gson.toJson(dataMap));
    }
    requestBuilder.addFormDataPart("data", data.toString());
    String url = "";
    if (!requestUrl.startsWith("http")) {
        url = Config.url + requestUrl;
    } else {
        url = requestUrl;
    }
    Request request = new Request.Builder().url(url).post(requestBuilder.build()).build();
    RetrofitClient.getInstance(ElectricPayApplication.instance).getOkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).build().newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {
            if (listener != null) {
                listener.onFailed("请检查您的网络");
            }
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            if (response.isSuccessful()) {
                String str = response.body().string();
                if (listener != null) {
                    listener.onResult(str);
                }
            } else {
                if (listener != null) {
                    listener.onFailed("请求失败");
                }
            }
        }
    });
}


public interface UploadListener {
    void onResult(String jsonResult);

    void onFailed(String errorMsg);

}

public static UploadListener listener;

public void setListener(UploadListener listener) {
    this.listener = listener;
}

private static Map<String, String> getRequestJsonHeader() {
    Map<String, String> head = new HashMap<>();
    head.put("SESSIONID", SharePreStore.get(ElectricPayApplication.instance, "tempSessionId"));
    head.put("PLAT", "3");// 对应值1:Symbian 2:WindowsMobile 3:Android 4:IOS
    head.put("CLIENTVERSION", "android" + android.os.Build.VERSION.RELEASE);// 客户端系统版本号
    head.put("SDKVERSION", "");// sdk应用版本号
    head.put("SESSIONID", SharePreStore.get(ElectricPayApplication.instance, "tempSessionId"));
    return head;
}

转载于:https://my.oschina.net/u/435726/blog/1586333