android之okhttp实现上传文件带进度条

android之okhttp实现上传文件带进度条

1封装okhttp

public class OkHttpTool {
    //日志标志
    private static String TAG = "OkHttpTool";
    //OkHttpClient
    private static final OkHttpClient myOkHttpClient;

    static {
        //========日志拦截器=========
        //Log拦截器
        HttpLoggingInterceptor loggingInterceptor =
                new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
            @Override
            public void log(@NonNull String message) {
                Log.i(TAG, message);
            }
        });
        //设置日志显示级别
        HttpLoggingInterceptor.Level level = HttpLoggingInterceptor.Level.BODY;
        loggingInterceptor.setLevel(level);

        //========cookie处理--让服务端记住app
        //这里是设置cookie,但是并没有做持久化处理;只是把cookie保存在内存中
        CookieJar cookieJar=new CookieJar() {
            private final HashMap<String, List<Cookie>> cookieStore = new HashMap<>();
            //保存cookie
            @Override
            public void saveFromResponse(@NonNull HttpUrl url, @NonNull List<Cookie> cookies) {
                cookieStore.put(url.host(), cookies);
            }
            //获取cookie
            @Override
            public List<Cookie> loadForRequest(@NonNull HttpUrl url) {
                List<Cookie> cookies = cookieStore.get(url.host());
                return cookies != null ? cookies : new ArrayList<Cookie>();
            }
        };

        //创建OkHttpClient
        myOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)//连接超时
                .writeTimeout(60, TimeUnit.SECONDS)//写入超时
                .readTimeout(60, TimeUnit.SECONDS)//读取超时
                .addInterceptor(loggingInterceptor)//添加日志处理拦截器
                .cookieJar(cookieJar)
                .build();
    }
 //================对外方法=====================

   
 //OkHttp请求回调中response.body().string()只能有效调用一次
//=====获取服务器响应信息回调接口======
public interface ResponseCallback {
    void onResponse(boolean isSuccess, int responseCode, String response, Exception exception);
}

   
    /**
     * POST 请求 文件上传显示进度条
     * @param url{String} 请求地址
     * @param parameters{Map<String, Object>} 请求参数
     * @param files{Map<String, File>} 上传的文件列表
     * @param

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OkHttp实现进度条上传文件,可以使用 RequestBody 的子类 ProgressRequestBody 来实现,具体代码如下: ``` public class ProgressRequestBody extends RequestBody { private RequestBody requestBody; private UploadProgressListener progressListener; public ProgressRequestBody(RequestBody requestBody, UploadProgressListener progressListener) { this.requestBody = requestBody; this.progressListener = progressListener; } @Override public MediaType contentType() { return requestBody.contentType(); } @Override public long contentLength() throws IOException { return requestBody.contentLength(); } @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink bufferedSink; if (sink instanceof Buffer) { bufferedSink = sink; } else { bufferedSink = Okio.buffer(sink); } CountingSink countingSink = new CountingSink(bufferedSink); BufferedSink progressSink = Okio.buffer(countingSink); requestBody.writeTo(progressSink); progressSink.flush(); progressListener.onProgress(countingSink.getContentLength()); } private class CountingSink extends ForwardingSink { private long contentLength; private long bytesWritten; public CountingSink(Sink delegate) { super(delegate); contentLength = -1; bytesWritten = 0; } @Override public void write(Buffer source, long byteCount) throws IOException { super.write(source, byteCount); if (contentLength == -1) { contentLength = contentLength(); } bytesWritten += byteCount; } public long getContentLength() { return contentLength; } public long getBytesWritten() { return bytesWritten; } } } ``` 其中,UploadProgressListener 为上传进度监听器,代码如下: ``` public interface UploadProgressListener { void onProgress(long bytesWritten); } ``` 在上传文件的时候,将 ProgressRequestBody 作为 RequestBody 使用即可: ``` OkHttpClient client = new OkHttpClient(); File file = new File("path/to/file"); RequestBody requestBody = new MultipartBody.Builder() .setType(MultipartBody.FORM) .addFormDataPart("file", file.getName(), new ProgressRequestBody(RequestBody.create(MediaType.parse("application/octet-stream"), file), new UploadProgressListener() { @Override public void onProgress(long bytesWritten) { // 更新上传进度 } })) .build(); Request request = new Request.Builder() .url("http://localhost/upload") .post(requestBody) .build(); Response response = client.newCall(request).execute(); ``` 在 ProgressRequestBody 中,每次写入数据的时候,都会回调 onProgress 方法,可以在这里更新上传进度

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值