package nodomain.freeyourgadget.gadgetbridge.womp;
|
|
import android.os.Handler;
|
import android.os.Looper;
|
|
import org.json.JSONObject;
|
|
import java.io.ByteArrayOutputStream;
|
import java.io.InputStream;
|
import java.io.OutputStream;
|
import java.net.HttpURLConnection;
|
import java.net.URL;
|
import java.nio.charset.StandardCharsets;
|
|
/**
|
* 调用 midway /app 接口。
|
*/
|
public final class WompApi {
|
public interface Callback {
|
void onResult(boolean ok, String body);
|
}
|
|
private WompApi() {}
|
|
public static void post(final String path, final JSONObject body, final Callback callback) {
|
new Thread(() -> {
|
HttpURLConnection conn = null;
|
try {
|
URL url = new URL(WompConfig.API_BASE + path);
|
conn = (HttpURLConnection) url.openConnection();
|
conn.setRequestMethod("POST");
|
conn.setConnectTimeout(15000);
|
conn.setReadTimeout(20000);
|
conn.setDoOutput(true);
|
conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
|
byte[] bytes = (body == null ? "{}" : body.toString()).getBytes(StandardCharsets.UTF_8);
|
conn.setFixedLengthStreamingMode(bytes.length);
|
OutputStream os = conn.getOutputStream();
|
os.write(bytes);
|
os.flush();
|
os.close();
|
int code = conn.getResponseCode();
|
InputStream is = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
|
if (is == null) {
|
deliver(callback, false, "{\"code\":0,\"message\":\"网络异常,请稍后重试\"}");
|
return;
|
}
|
ByteArrayOutputStream bos = new ByteArrayOutputStream();
|
byte[] buf = new byte[4096];
|
int n;
|
while ((n = is.read(buf)) > 0) {
|
bos.write(buf, 0, n);
|
}
|
is.close();
|
deliver(callback, code >= 200 && code < 300, bos.toString("UTF-8"));
|
} catch (java.net.UnknownHostException | java.net.ConnectException
|
| java.net.SocketTimeoutException | java.net.NoRouteToHostException e) {
|
deliver(callback, false, "{\"code\":0,\"message\":\"网络不通,请检查网络后重试\"}");
|
} catch (javax.net.ssl.SSLException e) {
|
deliver(callback, false, "{\"code\":0,\"message\":\"网络连接失败,请稍后重试\"}");
|
} catch (Exception e) {
|
deliver(callback, false, "{\"code\":0,\"message\":\"" + networkMessage(e) + "\"}");
|
} finally {
|
if (conn != null) {
|
conn.disconnect();
|
}
|
}
|
}).start();
|
}
|
|
private static String networkMessage(Exception e) {
|
String raw = e.getMessage() == null ? "" : e.getMessage().toLowerCase();
|
if (raw.contains("unable to resolve") || raw.contains("failed to connect")
|
|| raw.contains("timeout") || raw.contains("econnrefused")
|
|| raw.contains("network") || raw.contains("unreachable")) {
|
return "网络不通,请检查网络后重试";
|
}
|
return "网络异常,请稍后重试";
|
}
|
|
private static void deliver(final Callback callback, final boolean ok, final String body) {
|
if (callback == null) return;
|
new Handler(Looper.getMainLooper()).post(() -> callback.onResult(ok, body));
|
}
|
}
|