导航菜单

页面标题

页面副标题

FMG v6.0 - Request.java 源代码

正在查看: FMG v6.0 应用的 Request.java JAVA 源代码文件

本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。


package com.lorenzostanco.utils;

import android.os.AsyncTask;
import com.bumptech.glide.load.Key;
import com.google.firebase.messaging.Constants;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilderFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;

public abstract class Request<T> {
    public static final int DEFAULT_TIMEOUT = 60000;
    public static final int READ_BUFFER_SIZE = 4096;
    private AsyncTask<Void, Void, Object> asyncTask;
    protected int timeout = DEFAULT_TIMEOUT;
    protected HttpURLConnection connection = null;
    protected String requestMethod = "GET";
    protected Object requestBody = null;
    protected List<IEventListener<T>> eventListeners = new ArrayList();
    protected Map<String, String> requestHeaders = new HashMap();

    public static class EventListener<T> implements IEventListener<T> {
        @Override
        public void onCancel(final String url) {
        }

        @Override
        public void onComplete(final String url) {
        }

        @Override
        public void onError(final String url, final String code, final String message) {
        }

        @Override
        public void onRequest(final String url) {
        }

        @Override
        public void onSuccess(final String url, final T response) {
        }
    }

    public interface IEventListener<T> {
        void onCancel(String url);

        void onComplete(String url);

        void onError(String url, String code, String message);

        void onRequest(String url);

        void onSuccess(String url, T response);
    }

    public abstract String getRawResponse();

    protected abstract void postExecute(final String url, Object result);

    protected abstract Object requestInBackground(final String url) throws Exception;

    public Request<T> addEventListener(final IEventListener<T> l) {
        this.eventListeners.add(l);
        return this;
    }

    public Request<T> setTimeout(final int timeout) {
        this.timeout = timeout;
        return this;
    }

    public Request<T> setRequestHeaders(final Map<String, String> headers) {
        this.requestHeaders.clear();
        this.requestHeaders.putAll(headers);
        return this;
    }

    public Request<T> setRequestMethod(final String method) {
        this.requestMethod = method;
        return this;
    }

    public Request<T> setRequestBody(final Object body) {
        this.requestBody = body;
        if (this.requestMethod.toUpperCase().equals("GET")) {
            setRequestMethod("POST");
        }
        return this;
    }

    public Request<T> setRequestMethodAndBody(final String method, final Object body) {
        setRequestMethod(method);
        setRequestBody(body);
        return this;
    }

    public Request<T> clearRequestHeaders() {
        this.requestHeaders.clear();
        return this;
    }

    public Request<T> clearRequestBody() {
        this.requestBody = null;
        return this;
    }

    public void send(final String url) {
        cancel();
        AsyncTask<Void, Void, Object> asyncTask = new AsyncTask<Void, Void, Object>() {
            @Override
            protected void onPreExecute() {
                Iterator<IEventListener<T>> it2 = Request.this.eventListeners.iterator();
                while (it2.hasNext()) {
                    it2.next().onRequest(url);
                }
            }

            @Override
            public Object doInBackground(final Void... params) {
                try {
                    Object requestInBackground = Request.this.requestInBackground(url);
                    Request.this.disconnect();
                    return requestInBackground;
                } catch (Exception e) {
                    Request.this.disconnect();
                    return e;
                }
            }

            @Override
            protected void onPostExecute(final Object result) {
                if (isCancelled()) {
                    return;
                }
                Iterator<IEventListener<T>> it2 = Request.this.eventListeners.iterator();
                while (it2.hasNext()) {
                    it2.next().onComplete(url);
                }
                if (result instanceof Exception) {
                    Exception exc = (Exception) result;
                    String str = ((result instanceof SocketException) || (result instanceof UnknownHostException) || (result instanceof SocketTimeoutException)) ? "connection_error" : "unknown_error";
                    Iterator<IEventListener<T>> it3 = Request.this.eventListeners.iterator();
                    while (it3.hasNext()) {
                        it3.next().onError(url, str, exc.getClass().getSimpleName() + ": " + exc.getMessage());
                    }
                    return;
                }
                Request.this.postExecute(url, result);
            }
        };
        this.asyncTask = asyncTask;
        asyncTask.execute(new Void[0]);
    }

    public void cancel() {
        AsyncTask<Void, Void, Object> asyncTask = this.asyncTask;
        if (asyncTask != null) {
            asyncTask.cancel(true);
        }
        if (isRunning()) {
            String url = this.connection.getURL().toString();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Request.this.disconnect();
                }
            }).start();
            Iterator<IEventListener<T>> it2 = this.eventListeners.iterator();
            while (it2.hasNext()) {
                it2.next().onCancel(url);
            }
        }
    }

    public boolean isRunning() {
        return this.connection != null;
    }

    public void disconnect() {
        HttpURLConnection httpURLConnection = this.connection;
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
            this.connection = null;
        }
    }

    public static String requestStringSync(final String url, final Map<String, String> requestHeaders, final String requestMethod, final Object requestBody) throws IOException {
        return requestStringSync(url, requestHeaders, requestMethod, requestBody, DEFAULT_TIMEOUT);
    }

    public static String requestStringSync(final String url, final Map<String, String> requestHeaders, final String requestMethod, final Object requestBody, final int timeout) throws IOException {
        return requestStringSyncFromConnection((HttpURLConnection) new URL(url).openConnection(), requestHeaders, requestMethod, requestBody, timeout);
    }

    public static String requestStringSyncFromConnection(final HttpURLConnection connection, final Map<String, String> requestHeaders, final String requestMethod, final Object requestBody, final int timeout) throws IOException {
        connection.setConnectTimeout(timeout);
        connection.setReadTimeout(timeout);
        if (requestHeaders != null) {
            for (String str : requestHeaders.keySet()) {
                connection.setRequestProperty(str, requestHeaders.get(str));
            }
        }
        connection.setRequestMethod(requestMethod.toUpperCase());
        if (requestBody != null) {
            boolean z = true;
            connection.setDoOutput(true);
            if (!(requestBody instanceof JSONObject) && !(requestBody instanceof JSONArray)) {
                z = false;
            }
            connection.setRequestProperty("Content-Type", z ? "application/json" : "application/x-www-form-urlencoded");
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(connection.getOutputStream());
            outputStreamWriter.write(requestBody.toString());
            outputStreamWriter.flush();
            outputStreamWriter.close();
        } else {
            connection.setDoOutput(false);
        }
        int responseCode = connection.getResponseCode();
        if (responseCode >= 400) {
            throw new IOException((responseCode + " " + connection.getResponseMessage()).trim());
        }
        InputStreamReader inputStreamReader = new InputStreamReader(connection.getInputStream(), Key.STRING_CHARSET_NAME);
        char[] cArr = new char[4096];
        StringBuffer stringBuffer = new StringBuffer();
        while (true) {
            int read = inputStreamReader.read(cArr);
            if (read <= 0) {
                inputStreamReader.close();
                return stringBuffer.toString();
            }
            stringBuffer.append(cArr, 0, read);
        }
    }

    public static class JSON extends Request<JSONObject> {
        private String rawResponse = null;

        @Override
        protected Object requestInBackground(final String url) throws Exception {
            this.connection = (HttpURLConnection) new URL(url).openConnection();
            this.rawResponse = Request.requestStringSyncFromConnection(this.connection, this.requestHeaders, this.requestMethod, this.requestBody, this.timeout);
            return new JSONObject(this.rawResponse);
        }

        @Override
        protected void postExecute(final String url, final Object result) {
            JSONObject jSONObject = (JSONObject) result;
            if (jSONObject.optBoolean(Constants.IPC_BUNDLE_KEY_SEND_ERROR, false)) {
                Iterator<IEventListener<T>> it2 = this.eventListeners.iterator();
                while (it2.hasNext()) {
                    it2.next().onError(url, jSONObject.optString("error_code", "unknown_error"), jSONObject.optString("error_message", "(unknown error)"));
                }
            } else {
                Iterator<IEventListener<T>> it3 = this.eventListeners.iterator();
                while (it3.hasNext()) {
                    it3.next().onSuccess(url, jSONObject);
                }
            }
        }

        @Override
        public String getRawResponse() {
            return this.rawResponse;
        }

        public static JSONObject requestJSONObjectSync(final String url, final Map<String, String> requestHeaders, final String requestMethod, final String requestBody) throws IOException, JSONException {
            return requestJSONObjectSync(url, requestHeaders, requestMethod, requestBody, Request.DEFAULT_TIMEOUT);
        }

        public static JSONObject requestJSONObjectSync(final String url, final Map<String, String> requestHeaders, final String requestMethod, final String requestBody, final int timeout) throws IOException, JSONException {
            return new JSONObject(requestStringSync(url, requestHeaders, requestMethod, requestBody, timeout));
        }

        public static JSONArray requestJSONArraySync(final String url, final Map<String, String> requestHeaders, final String requestMethod, final String requestBody) throws IOException, JSONException {
            return requestJSONArraySync(url, requestHeaders, requestMethod, requestBody, Request.DEFAULT_TIMEOUT);
        }

        public static JSONArray requestJSONArraySync(final String url, final Map<String, String> requestHeaders, final String requestMethod, final String requestBody, final int timeout) throws IOException, JSONException {
            return new JSONArray(requestStringSync(url, requestHeaders, requestMethod, requestBody, timeout));
        }
    }

    public static class XML extends Request<Document> {
        private String rawResponse = null;

        @Override
        protected Object requestInBackground(final String url) throws Exception {
            this.connection = (HttpURLConnection) new URL(url).openConnection();
            this.rawResponse = Request.requestStringSyncFromConnection(this.connection, this.requestHeaders, this.requestMethod, this.requestBody, this.timeout);
            StringReader stringReader = new StringReader(this.rawResponse);
            Document parse = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(stringReader));
            stringReader.close();
            return parse;
        }

        @Override
        protected void postExecute(final String url, final Object result) {
            Document document = (Document) result;
            Element documentElement = document.getDocumentElement();
            if (documentElement.hasAttribute(Constants.IPC_BUNDLE_KEY_SEND_ERROR) && documentElement.getAttribute(Constants.IPC_BUNDLE_KEY_SEND_ERROR).equals("1")) {
                Iterator<IEventListener<T>> it2 = this.eventListeners.iterator();
                while (it2.hasNext()) {
                    it2.next().onError(url, documentElement.hasAttribute("error_code") ? documentElement.getAttribute("error_code") : "unknown_error", documentElement.hasAttribute("error_message") ? documentElement.getAttribute("error_message") : "(unknown error)");
                }
            } else {
                Iterator<IEventListener<T>> it3 = this.eventListeners.iterator();
                while (it3.hasNext()) {
                    it3.next().onSuccess(url, document);
                }
            }
        }

        @Override
        public String getRawResponse() {
            return this.rawResponse;
        }

        public static Document requestXMLDocumentSync(final String url, final Map<String, String> requestHeaders, final String requestMethod, final String requestBody) throws Exception {
            return requestXMLDocumentSync(url, requestHeaders, requestMethod, requestBody, Request.DEFAULT_TIMEOUT);
        }

        public static Document requestXMLDocumentSync(final String url, final Map<String, String> requestHeaders, final String requestMethod, final String requestBody, final int timeout) throws Exception {
            StringReader stringReader = new StringReader(requestStringSync(url, requestHeaders, requestMethod, requestBody, timeout));
            Document parse = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(stringReader));
            stringReader.close();
            return parse;
        }
    }

    public static class PlainText extends Request<String> {
        private String rawResponse = null;

        @Override
        protected Object requestInBackground(final String url) throws Exception {
            this.connection = (HttpURLConnection) new URL(url).openConnection();
            String requestStringSyncFromConnection = Request.requestStringSyncFromConnection(this.connection, this.requestHeaders, this.requestMethod, this.requestBody, this.timeout);
            this.rawResponse = requestStringSyncFromConnection;
            return requestStringSyncFromConnection;
        }

        @Override
        protected void postExecute(String str, Object obj) {
            Iterator<IEventListener<T>> it2 = this.eventListeners.iterator();
            while (it2.hasNext()) {
                it2.next().onSuccess(str, (String) obj);
            }
        }

        @Override
        public String getRawResponse() {
            return this.rawResponse;
        }
    }
}