-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathLocationDetectUtil.java
More file actions
68 lines (57 loc) · 2.19 KB
/
LocationDetectUtil.java
File metadata and controls
68 lines (57 loc) · 2.19 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
package i18nupdatemod.util;
import org.apache.commons.io.IOUtils;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class LocationDetectUtil {
private static Boolean cached = null;
private static final String[][] GEO_APIS = {
{"Kugou", "https://mips.kugou.com/check/iscn?&format=json"},
{"IP.SB", "https://api.ip.sb/geoip"}
};
public static boolean isMainlandChina() {
if (cached != null) {
return cached;
}
for (String[] api : GEO_APIS) {
Boolean result = tryApi(api[0], api[1]);
if (result != null) {
cached = result;
return cached;
}
}
cached = false;
return false;
}
private static Boolean tryApi(String name, String url) {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(5000);
if (conn.getResponseCode() == 200) {
String response = IOUtils.toString(conn.getInputStream(), StandardCharsets.UTF_8);
boolean isChina = parseResponse(response);
Log.info("Location Detected (" + name + " API): " + (isChina ? "Inside mainland China" : "Outside mainland China"));
return isChina;
}
} catch (Exception e) {
Log.debug(name + " API detection failed: " + e.getMessage());
}
return null;
}
private static boolean parseResponse(String response) {
response = response.trim();
// Kugou API JSON: {"flag": 1} 或 {"flag": true}
if (response.contains("\"flag\":1") || response.contains("\"flag\": 1") ||response.contains("\"flag\":true") || response.contains("\"flag\": true")) {
return true;
}
// IP.SB API JSON: {"country_code": "CN"}
if (response.contains("\"country_code\":\"CN\"") || response.contains("\"country_code\": \"CN\"")) {
return true;
}
return false;
}
public static void resetCache() {
cached = null;
}
}