wangzhibo
4 天以前 ae6f40460dcd56af6c5f60ba52c883854c3bac55
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
84
85
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));
    }
}