admin
2021-07-28 c0269fcfa876b9c5cf309b2006462b4d09c5ef95
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package com.lcjian.library.okhttp.request;
 
import java.io.IOException;
 
import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;
 
/**
 * Decorates an OkHttp request body to count the number of bytes written when writing it. Can
 * decorate any request body, but is most useful for tracking the upload progress of large
 * multipart requests.
 *
 * @author Leo Nikkilä
 */
public class CountingRequestBody extends RequestBody
{
 
    protected RequestBody delegate;
    protected Listener listener;
 
    protected CountingSink countingSink;
 
    public CountingRequestBody(RequestBody delegate, Listener listener)
    {
        this.delegate = delegate;
        this.listener = listener;
    }
 
    @Override
    public MediaType contentType()
    {
        return delegate.contentType();
    }
 
    @Override
    public long contentLength()
    {
        try
        {
            return delegate.contentLength();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
        return -1;
    }
 
    @Override
    public void writeTo(BufferedSink sink) throws IOException
    {
 
        countingSink = new CountingSink(sink);
        BufferedSink bufferedSink = Okio.buffer(countingSink);
 
        delegate.writeTo(bufferedSink);
 
        bufferedSink.flush();
    }
 
    protected final class CountingSink extends ForwardingSink
    {
 
        private long bytesWritten = 0;
 
        public CountingSink(Sink delegate)
        {
            super(delegate);
        }
 
        @Override
        public void write(Buffer source, long byteCount) throws IOException
        {
            super.write(source, byteCount);
 
            bytesWritten += byteCount;
            listener.onRequestProgress(bytesWritten, contentLength());
        }
 
    }
 
    public interface Listener
    {
        void onRequestProgress(long bytesWritten, long contentLength);
    }
 
}