admin
2022-01-07 8dfe5354073b700af45d5cb472dd5f003e6f3f25
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
92
93
94
95
package com.ysvideo.zhibo.lib.common.okhttp.request;
 
 
import com.ysvideo.zhibo.lib.common.okhttp.callback.Callback;
import com.ysvideo.zhibo.lib.common.okhttp.utils.Exceptions;
 
import java.util.Map;
 
import okhttp3.Headers;
import okhttp3.Request;
import okhttp3.RequestBody;
 
/**
 * Created by zhy on 15/11/6.
 */
public abstract class OkHttpRequest
{
    protected String url;
    protected Object tag;
    protected Map<String, String> params;
    protected Map<String, String> headers;
    protected int id;
 
    protected Request.Builder builder = new Request.Builder();
 
    protected OkHttpRequest(String url, Object tag,
                            Map<String, String> params, Map<String, String> headers,int id)
    {
        this.url = url;
        this.tag = tag;
        this.params = params;
        this.headers = headers;
        this.id = id ;
 
        if (url == null)
        {
            Exceptions.illegalArgument("url can not be null.");
        }
 
        initBuilder();
    }
 
 
 
    /**
     * 初始化一些基本参数 url , tag , headers
     */
    private void initBuilder()
    {
        builder.url(url).tag(tag);
        appendHeaders();
    }
 
    protected abstract RequestBody buildRequestBody();
 
    protected RequestBody wrapRequestBody(RequestBody requestBody, final Callback callback)
    {
        return requestBody;
    }
 
    protected abstract Request buildRequest(RequestBody requestBody);
 
    public RequestCall build()
    {
        return new RequestCall(this);
    }
 
 
    public Request generateRequest(Callback callback)
    {
        RequestBody requestBody = buildRequestBody();
        RequestBody wrappedRequestBody = wrapRequestBody(requestBody, callback);
        Request request = buildRequest(wrappedRequestBody);
        return request;
    }
 
 
    protected void appendHeaders()
    {
        Headers.Builder headerBuilder = new Headers.Builder();
        if (headers == null || headers.isEmpty()) return;
 
        for (String key : headers.keySet())
        {
            headerBuilder.add(key, headers.get(key));
        }
        builder.headers(headerBuilder.build());
    }
 
    public int getId()
    {
        return id  ;
    }
 
}