Skip to content

Commit fbec20a

Browse files
change API IP lookup
1 parent 2745b2a commit fbec20a

1 file changed

Lines changed: 8 additions & 13 deletions

File tree

  • app/src/main/java/io/nekohasekai/sagernet/widget

app/src/main/java/io/nekohasekai/sagernet/widget/StatsBar.kt

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -145,29 +145,28 @@ class StatsBar @JvmOverloads constructor(
145145
private suspend fun getPublicIpInfo(): String {
146146
return withContext(Dispatchers.IO) {
147147
try {
148-
val url = URL("https://ipwhois.app/json/")
148+
val url = URL("https://ipapi.co/json/")
149149
val connection = url.openConnection() as HttpURLConnection
150150
connection.requestMethod = "GET"
151151
connection.connectTimeout = 5000
152152
connection.readTimeout = 5000
153-
153+
connection.setRequestProperty("User-Agent", "Mozilla/5.0")
154154
val response = connection.inputStream.bufferedReader().use { it.readText() }
155155
val json = JSONObject(response)
156156

157-
if (json.getBoolean("success")) {
157+
if (!json.has("error")) {
158158
val ip = json.getString("ip")
159-
val country = json.getString("country")
159+
val country = json.getString("country_name")
160160
val countryCode = json.getString("country_code")
161-
162-
val flag = getFlagEmoji(countryCode)
163-
161+
val flag = getFlagEmoji(countryCode)
164162
"IP: $ip ($flag $country)"
165163
} else {
166-
context.getString(R.string.ip_info_failed)
164+
val reason = json.getString("reason")
165+
"IP Fail: $reason"
167166
}
168167
} catch (e: Exception) {
169168
e.printStackTrace()
170-
"IP Fail: ${e.javaClass.simpleName}"
169+
context.getString(R.string.ip_info_failed)
171170
}
172171
}
173172
}
@@ -191,12 +190,9 @@ class StatsBar @JvmOverloads constructor(
191190
onMainDispatcher {
192191
isEnabled = true
193192
setStatus(latencyResult)
194-
195193
if (DataStore.connectionTestWithIp) {
196-
197194
activity.lifecycleScope.launch {
198195
val ipInfo = getPublicIpInfo()
199-
200196
setStatus("$latencyResult$ipInfo")
201197
}
202198
}
@@ -207,7 +203,6 @@ class StatsBar @JvmOverloads constructor(
207203
onMainDispatcher {
208204
isEnabled = true
209205
setStatus(app.getText(R.string.connection_test_testing))
210-
211206
activity.snackbar(
212207
app.getString(
213208
R.string.connection_test_error, e.readableMessage

0 commit comments

Comments
 (0)