OKHttpUtils.java
2.89 KB
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
import okhttp3.*;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* Created by youjie on 2018/4/27.
*/
public class OKHttpUtils {
private static final String TAG = "HttpUtils";
public static final MediaType MEDIA_TYPE_MARKDOWN
= MediaType.parse("text/x-markdown; charset=utf-8");
private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
public static void getAsycHttp(String url) {
OkHttpClient mOkHttpClient = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url(url);
requestBuilder.method("GET",null);
Request request = requestBuilder.build();
Call mcall= mOkHttpClient.newCall(request);
mcall.enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
}
public void onResponse(Call call, Response response) throws IOException {
if (null != response.cacheResponse()) {
String str = response.cacheResponse().toString();
System.out.println( "cache---" + str);
} else {
response.body().string();
String str = response.networkResponse().toString();
System.out.println( "network---" + str);
}
}
});
}
public static void commonPost(String url, String jsonString) {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(JSON, jsonString);
OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.connectTimeout(30, TimeUnit.SECONDS).build();
Request request= null;
request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Call call = mOkHttpClient.newCall(request);
call.enqueue(new Callback() {
public void onFailure(Call call, IOException e) {
System.out.println( "onFailure :" + call.toString());
// e.printStackTrace();
System.exit(1);
}
public void onResponse(Call call, Response response) throws IOException {
String str = response.body().string();
Headers headers = response.headers();
List<String> cookies = headers.values("Set-Cookie");
if (cookies.size() > 0) {
String session = cookies.get(0);
String result = session.substring(0, session.indexOf(";"));
System.out.println( "cookies:" + result);
}
System.out.println("onResponse:" + str);
System.exit(0);
}
});
}
}