Android网络相关

抓包工具

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
// https://stackoverflow.com/questions/17654631/android-webview-read-cookies/20241864
public String getCookie(String siteName, String cookieName) {
String cookieValue = null;

CookieManager cookieManager = CookieManager.getInstance();
String cookies = cookieManager.getCookie(siteName);
if (cookies != null) {
String[] temp = cookies.split(";");
for (String ar1 : temp) {
if (ar1.contains(cookieName)) {
String[] temp1 = ar1.split("=");
cookieValue = temp1[1];
}
}
}
return cookieValue;
}

// 使用
File file = new File(filePath);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(), RequestBody.create(MediaType.parse("image/*"), file))
.build();

Request request = new Request.Builder()
.url(callBack.getUrl())
.post(requestBody)
.addHeader("Accept", "*/*")
.addHeader("cookie", "ci_session=" + getCookie(APP_URL, "ci_session"))
.build();
client.newCall(request).enqueue(callBack);
1
2
3
4
5
6
7
// https://stackoverflow.com/questions/34881775/automatic-cookie-handling-with-okhttp-3/35346473
// https://github.com/franmontiel/PersistentCookieJar
CookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(),
new SharedPrefsCookiePersistor(context));
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.cookieJar(cookieJar)
.build();

获取网络时间

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

public class Utime {
private static final String URL_DEFAULT = "http://lyloou.com";
/**
*
* 获取时间戳(始终使用网络时间,如果获取网络时间失败,才使用本地时间)
* 注意该方法涉及网络操作,不要在主线程中调用
* 返回的是以秒为单位的时间字符串
*/
public static String getTimeStamp(String url) {

final String urlRrBase = getBaseUrl(url);
final long phoneTime = System.currentTimeMillis() / 1000;

try {
// 生成连接对象
URLConnection uc = new URL(urlRrBase).openConnection();
// 发出连接
uc.connect();
long webTimeMillis = uc.getDate();
// 读取网站日期时间
long webTime = webTimeMillis / 1000;
return String.valueOf(webTime);
} catch (Exception e) {
return String.valueOf(phoneTime);
}
}

private static String getBaseUrl(String url) {
if (TextUtils.isEmpty(url)) {
return URL_DEFAULT;
}

try {
URI uri = new URI(url);
return uri.getScheme() + "://" + uri.getHost();
} catch (Exception e) {
return URL_DEFAULT;
}

}
}