okhttp使用

文章目录
  1. 异步、同步下载
    1. 一.返回结果接口
    2. 二.工具类

异步、同步下载

一.返回结果接口

public interface IDownloadResult {

    public void success(String str);
    public void  error(String str);
}

二.工具类

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
public class OKHttp {

private static OKHttp okhttp = null;
private OkHttpClient client;

private OKHttp(){

}

public static OKHttp getInstance(){
if(okhttp == null){
synchronized (OKHttp.class){
if(okhttp == null)
okhttp = new OKHttp();
}
}
return okhttp;
}

IDownloadResult result;

public void setResult(IDownloadResult result){
this.result = result;
}

//返回Client对象
private OkHttpClient getClient(){
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(5000, TimeUnit.MILLISECONDS)
.readTimeout(2000,TimeUnit.MILLISECONDS)
.addInterceptor(new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
/**
* 返回response,先获得request再通过调用proceed方法得到response
*/
Request request = chain.request();

Log.d("amy", String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);

return response;
}
})
.build();
return client;
}

/**
* 异步下载
*/
public void downLoadJsonStr(){

client = getClient();

final Request request = new Request.Builder().get().
url(Strings.URL_STR).build();

client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
result.error(e.getMessage());
}

@Override
public void onResponse(Call call, Response response) throws IOException {
result.success(response.body().string());
}
});
}

//同步下载(调用时需要创建线程)
public void downLoadJsonStr_tongbu(){
client = getClient();

Request request = new Request.Builder().url(Strings.URL_STR).build();

try {
Response response = client.newCall(request).execute();
result.success(response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
}