HttpRequest.java

/*
 * Decompiled with CFR 0_132.
 * 
 * Could not load the following classes:
 *  android.annotation.TargetApi
 *  android.net.Uri
 *  android.os.Build
 *  android.os.Build$VERSION
 *  android.text.TextUtils
 */
package org.xutils.http.request;

import android.annotation.TargetApi;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.CookieStore;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;
import org.xutils.cache.DiskCacheEntity;
import org.xutils.cache.LruDiskCache;
import org.xutils.common.util.IOUtil;
import org.xutils.common.util.KeyValue;
import org.xutils.common.util.LogUtil;
import org.xutils.ex.HttpException;
import org.xutils.http.BaseParams;
import org.xutils.http.HttpMethod;
import org.xutils.http.ProgressHandler;
import org.xutils.http.RequestParams;
import org.xutils.http.app.RedirectHandler;
import org.xutils.http.app.RequestInterceptListener;
import org.xutils.http.body.ProgressBody;
import org.xutils.http.body.RequestBody;
import org.xutils.http.cookie.DbCookieStore;
import org.xutils.http.loader.Loader;
import org.xutils.http.request.UriRequest;

public class HttpRequest
extends UriRequest {
    private String cacheKey = null;
    private boolean isLoading = false;
    private InputStream inputStream = null;
    private HttpURLConnection connection = null;
    private int responseCode = 0;
    private static final CookieManager COOKIE_MANAGER = new CookieManager(DbCookieStore.INSTANCE, CookiePolicy.ACCEPT_ALL);

    HttpRequest(RequestParams params, Type loadType) throws Throwable {
        super(params, loadType);
    }

    @Override
    protected String buildQueryUrl(RequestParams params) {
        String uri = params.getUri();
        StringBuilder queryBuilder = new StringBuilder(uri);
        if (!uri.contains("?")) {
            queryBuilder.append("?");
        } else if (!uri.endsWith("?")) {
            queryBuilder.append("&");
        }
        List queryParams = params.getQueryStringParams();
        if (queryParams != null) {
            for (KeyValue kv : queryParams) {
                String name = kv.key;
                String value = kv.getValueStr();
                if (TextUtils.isEmpty((CharSequence)name) || value == null) continue;
                queryBuilder.append(Uri.encode((String)name, (String)params.getCharset())).append("=").append(Uri.encode((String)value, (String)params.getCharset())).append("&");
            }
        }
        if (queryBuilder.charAt(queryBuilder.length() - 1) == '&') {
            queryBuilder.deleteCharAt(queryBuilder.length() - 1);
        }
        if (queryBuilder.charAt(queryBuilder.length() - 1) == '?') {
            queryBuilder.deleteCharAt(queryBuilder.length() - 1);
        }
        return queryBuilder.toString();
    }

    @Override
    public String getRequestUri() {
        URL url;
        String result = this.queryUrl;
        if (this.connection != null && (url = this.connection.getURL()) != null) {
            result = url.toString();
        }
        return result;
    }

    @TargetApi(value=19)
    @Override
    public void sendRequest() throws Throwable {
        Object cookies;
        SSLSocketFactory sslSocketFactory;
        Object headers;
        RequestBody body2;
        this.isLoading = false;
        this.responseCode = 0;
        URL url = new URL(this.queryUrl);
        Proxy proxy = this.params.getProxy();
        this.connection = proxy != null ? (HttpURLConnection)url.openConnection(proxy) : (HttpURLConnection)url.openConnection();
        if (Build.VERSION.SDK_INT < 19) {
            this.connection.setRequestProperty("Connection", "close");
        }
        this.connection.setReadTimeout(this.params.getReadTimeout());
        this.connection.setConnectTimeout(this.params.getConnectTimeout());
        this.connection.setInstanceFollowRedirects(this.params.getRedirectHandler() == null);
        if (this.connection instanceof HttpsURLConnection && (sslSocketFactory = this.params.getSslSocketFactory()) != null) {
            ((HttpsURLConnection)this.connection).setSSLSocketFactory(sslSocketFactory);
        }
        if (this.params.isUseCookie()) {
            try {
                Map<String, List<String>> singleMap = COOKIE_MANAGER.get(url.toURI(), new HashMap<String, List<String>>(0));
                cookies = singleMap.get("Cookie");
                if (cookies != null) {
                    this.connection.setRequestProperty("Cookie", TextUtils.join((CharSequence)";", (Iterable)cookies));
                }
            }
            catch (Throwable ex) {
                LogUtil.e(ex.getMessage(), ex);
            }
        }
        if ((headers = this.params.getHeaders()) != null) {
            cookies = headers.iterator();
            while (cookies.hasNext()) {
                BaseParams.Header header = (BaseParams.Header)cookies.next();
                String name = header.key;
                String value = header.getValueStr();
                if (TextUtils.isEmpty((CharSequence)name) || TextUtils.isEmpty((CharSequence)value)) continue;
                if (header.setHeader) {
                    this.connection.setRequestProperty(name, value);
                    continue;
                }
                this.connection.addRequestProperty(name, value);
            }
        }
        if (this.requestInterceptListener != null) {
            this.requestInterceptListener.beforeRequest(this);
        }
        HttpMethod method = this.params.getMethod();
        try {
            this.connection.setRequestMethod(method.toString());
        }
        catch (ProtocolException ex) {
            try {
                Field methodField = HttpURLConnection.class.getDeclaredField("method");
                methodField.setAccessible(true);
                methodField.set(this.connection, method.toString());
            }
            catch (Throwable ignored) {
                throw ex;
            }
        }
        if (HttpMethod.permitsRequestBody(method) && (body2 = this.params.getRequestBody()) != null) {
            String contentType;
            long contentLength;
            if (body2 instanceof ProgressBody) {
                ((ProgressBody)body2).setProgressHandler(this.progressHandler);
            }
            if (!TextUtils.isEmpty((CharSequence)(contentType = body2.getContentType()))) {
                this.connection.setRequestProperty("Content-Type", contentType);
            }
            if ((contentLength = body2.getContentLength()) < 0L) {
                this.connection.setChunkedStreamingMode(262144);
            } else if (contentLength < Integer.MAX_VALUE) {
                this.connection.setFixedLengthStreamingMode((int)contentLength);
            } else if (Build.VERSION.SDK_INT >= 19) {
                this.connection.setFixedLengthStreamingMode(contentLength);
            } else {
                this.connection.setChunkedStreamingMode(262144);
            }
            this.connection.setRequestProperty("Content-Length", String.valueOf(contentLength));
            this.connection.setDoOutput(true);
            body2.writeTo(this.connection.getOutputStream());
        }
        if (this.params.isUseCookie()) {
            try {
                headers = this.connection.getHeaderFields();
                if (headers != null) {
                    COOKIE_MANAGER.put(url.toURI(), (Map<String, List<String>>)headers);
                }
            }
            catch (Throwable ex) {
                LogUtil.e(ex.getMessage(), ex);
            }
        }
        this.responseCode = this.connection.getResponseCode();
        if (this.requestInterceptListener != null) {
            this.requestInterceptListener.afterRequest(this);
        }
        if (this.responseCode == 204 || this.responseCode == 205) {
            throw new HttpException(this.responseCode, this.getResponseMessage());
        }
        if (this.responseCode >= 300) {
            HttpException httpException = new HttpException(this.responseCode, this.getResponseMessage());
            try {
                httpException.setResult(IOUtil.readStr(this.getInputStream(), this.params.getCharset()));
            }
            catch (Throwable body2) {
                // empty catch block
            }
            LogUtil.e(httpException.toString() + ", url: " + this.queryUrl);
            throw httpException;
        }
        this.isLoading = true;
    }

    @Override
    public boolean isLoading() {
        return this.isLoading;
    }

    @Override
    public String getCacheKey() {
        if (this.cacheKey == null) {
            this.cacheKey = this.params.getCacheKey();
            if (TextUtils.isEmpty((CharSequence)this.cacheKey)) {
                this.cacheKey = this.params.toString();
            }
        }
        return this.cacheKey;
    }

    @Override
    public Object loadResult() throws Throwable {
        this.isLoading = true;
        return super.loadResult();
    }

    @Override
    public Object loadResultFromCache() throws Throwable {
        this.isLoading = true;
        DiskCacheEntity cacheEntity = LruDiskCache.getDiskCache(this.params.getCacheDirName()).setMaxSize(this.params.getCacheSize()).get(this.getCacheKey());
        if (cacheEntity != null) {
            if (HttpMethod.permitsCache(this.params.getMethod())) {
                String eTag;
                Date lastModified = cacheEntity.getLastModify();
                if (lastModified.getTime() > 0L) {
                    this.params.setHeader("If-Modified-Since", HttpRequest.toGMTString(lastModified));
                }
                if (!TextUtils.isEmpty((CharSequence)(eTag = cacheEntity.getEtag()))) {
                    this.params.setHeader("If-None-Match", eTag);
                }
            }
            return this.loader.loadFromCache(cacheEntity);
        }
        return null;
    }

    @Override
    public void clearCacheHeader() {
        this.params.setHeader("If-Modified-Since", null);
        this.params.setHeader("If-None-Match", null);
    }

    @Override
    public InputStream getInputStream() throws IOException {
        if (this.connection != null && this.inputStream == null) {
            this.inputStream = this.connection.getResponseCode() >= 400 ? this.connection.getErrorStream() : this.connection.getInputStream();
        }
        return this.inputStream;
    }

    @Override
    public void close() throws IOException {
        if (this.inputStream != null) {
            IOUtil.closeQuietly(this.inputStream);
            this.inputStream = null;
        }
        if (this.connection != null) {
            this.connection.disconnect();
        }
    }

    @Override
    public long getContentLength() {
        long result = 0L;
        if (this.connection != null) {
            try {
                result = this.connection.getContentLength();
            }
            catch (Throwable ex) {
                LogUtil.e(ex.getMessage(), ex);
            }
            if (result < 1L) {
                try {
                    result = this.getInputStream().available();
                }
                catch (Throwable ex) {}
            }
        } else {
            try {
                result = this.getInputStream().available();
            }
            catch (Throwable ex) {
                // empty catch block
            }
        }
        return result;
    }

    @Override
    public int getResponseCode() throws IOException {
        if (this.connection != null) {
            return this.responseCode;
        }
        if (this.getInputStream() != null) {
            return 200;
        }
        return 404;
    }

    @Override
    public String getResponseMessage() throws IOException {
        if (this.connection != null) {
            return URLDecoder.decode(this.connection.getResponseMessage(), this.params.getCharset());
        }
        return null;
    }

    @Override
    public long getExpiration() {
        if (this.connection == null) {
            return -1L;
        }
        long expiration = -1L;
        String cacheControl = this.connection.getHeaderField("Cache-Control");
        if (!TextUtils.isEmpty((CharSequence)cacheControl)) {
            StringTokenizer tok = new StringTokenizer(cacheControl, ",");
            while (tok.hasMoreTokens()) {
                String token = tok.nextToken().trim().toLowerCase();
                if (!token.startsWith("max-age")) continue;
                int eqIdx = token.indexOf(61);
                if (eqIdx <= 0) break;
                try {
                    String value = token.substring(eqIdx + 1).trim();
                    long seconds = Long.parseLong(value);
                    if (seconds <= 0L) break;
                    expiration = System.currentTimeMillis() + seconds * 1000L;
                }
                catch (Throwable ex) {
                    LogUtil.e(ex.getMessage(), ex);
                }
                break;
            }
        }
        if (expiration <= 0L) {
            expiration = this.connection.getExpiration();
        }
        if (expiration <= 0L && this.params.getCacheMaxAge() > 0L) {
            expiration = System.currentTimeMillis() + this.params.getCacheMaxAge();
        }
        if (expiration <= 0L) {
            expiration = Long.MAX_VALUE;
        }
        return expiration;
    }

    @Override
    public long getLastModified() {
        return this.getHeaderFieldDate("Last-Modified", System.currentTimeMillis());
    }

    @Override
    public String getETag() {
        if (this.connection == null) {
            return null;
        }
        return this.connection.getHeaderField("ETag");
    }

    @Override
    public String getResponseHeader(String name) {
        if (this.connection == null) {
            return null;
        }
        return this.connection.getHeaderField(name);
    }

    @Override
    public Map<String, List<String>> getResponseHeaders() {
        if (this.connection == null) {
            return null;
        }
        return this.connection.getHeaderFields();
    }

    @Override
    public long getHeaderFieldDate(String name, long defaultValue) {
        if (this.connection == null) {
            return defaultValue;
        }
        return this.connection.getHeaderFieldDate(name, defaultValue);
    }

    private static String toGMTString(Date date) {
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM y HH:mm:ss 'GMT'", Locale.US);
        TimeZone gmtZone = TimeZone.getTimeZone("GMT");
        sdf.setTimeZone(gmtZone);
        GregorianCalendar gc = new GregorianCalendar(gmtZone);
        gc.setTimeInMillis(date.getTime());
        return sdf.format(date);
    }
}