翰林优商.apk(点击下载) / HttpRequest.java


package com.duoyou.task.sdk.xutils.http.request;

import android.os.Build;
import android.text.TextUtils;
import com.duoyou.task.sdk.xutils.cache.DiskCacheEntity;
import com.duoyou.task.sdk.xutils.cache.LruDiskCache;
import com.duoyou.task.sdk.xutils.common.util.IOUtil;
import com.duoyou.task.sdk.xutils.common.util.KeyValue;
import com.duoyou.task.sdk.xutils.common.util.LogUtil;
import com.duoyou.task.sdk.xutils.ex.HttpException;
import com.duoyou.task.sdk.xutils.http.BaseParams;
import com.duoyou.task.sdk.xutils.http.HttpMethod;
import com.duoyou.task.sdk.xutils.http.RequestParams;
import com.duoyou.task.sdk.xutils.http.app.RequestInterceptListener;
import com.duoyou.task.sdk.xutils.http.app.ResponseParser;
import com.duoyou.task.sdk.xutils.http.body.ProgressBody;
import com.duoyou.task.sdk.xutils.http.body.RequestBody;
import com.duoyou.task.sdk.xutils.http.cookie.DbCookieStore;
import com.mbridge.msdk.foundation.download.Command;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.TimeZone;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSocketFactory;

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

    public HttpRequest(RequestParams requestParams, Type type) {
        super(requestParams, type);
    }

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

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public String buildQueryUrl(RequestParams requestParams) {
        String uri = requestParams.getUri();
        StringBuilder sb = new StringBuilder(uri);
        if (!uri.contains("?")) {
            sb.append("?");
        } else if (!uri.endsWith("?")) {
            sb.append("&");
        }
        List<KeyValue> queryStringParams = requestParams.getQueryStringParams();
        if (queryStringParams != null) {
            for (KeyValue keyValue : queryStringParams) {
                String str = keyValue.key;
                String valueStrOrNull = keyValue.getValueStrOrNull();
                if (!TextUtils.isEmpty(str) && valueStrOrNull != null) {
                    sb.append(URLEncoder.encode(str, requestParams.getCharset()).replaceAll("\\+", "%20"));
                    sb.append("=");
                    sb.append(URLEncoder.encode(valueStrOrNull, requestParams.getCharset()).replaceAll("\\+", "%20"));
                    sb.append("&");
                }
            }
        }
        if (sb.charAt(sb.length() - 1) == '&') {
            sb.deleteCharAt(sb.length() - 1);
        }
        if (sb.charAt(sb.length() - 1) == '?') {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public void clearCacheHeader() {
        this.params.setHeader("If-Modified-Since", null);
        this.params.setHeader("If-None-Match", null);
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest, java.io.Closeable, java.lang.AutoCloseable
    public void close() {
        InputStream inputStream2 = this.inputStream;
        if (inputStream2 != null) {
            IOUtil.closeQuietly(inputStream2);
            this.inputStream = null;
        }
        HttpURLConnection httpURLConnection = this.connection;
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public String getCacheKey() {
        if (this.cacheKey == null) {
            String cacheKey2 = this.params.getCacheKey();
            this.cacheKey = cacheKey2;
            if (TextUtils.isEmpty(cacheKey2)) {
                this.cacheKey = this.params.toString();
            }
        }
        return this.cacheKey;
    }

    /* JADX WARNING: Removed duplicated region for block: B:12:0x0021 A[SYNTHETIC, Splitter:B:12:0x0021] */
    /* JADX WARNING: Removed duplicated region for block: B:18:? A[RETURN, SYNTHETIC] */
    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public long getContentLength() {
        long j;
        HttpURLConnection httpURLConnection = this.connection;
        if (httpURLConnection != null) {
            try {
                String headerField = httpURLConnection.getHeaderField("content-length");
                if (headerField != null) {
                    j = Long.parseLong(headerField);
                    if (j < 1) {
                        return j;
                    }
                    try {
                        return (long) getInputStream().available();
                    } catch (Throwable unused) {
                        return j;
                    }
                }
            } catch (Throwable th) {
                LogUtil.e(th.getMessage(), th);
            }
        }
        j = -1;
        if (j < 1) {
        }
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public String getETag() {
        HttpURLConnection httpURLConnection = this.connection;
        if (httpURLConnection == null) {
            return null;
        }
        return httpURLConnection.getHeaderField(Command.HTTP_HEADER_ETAG);
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public long getExpiration() {
        HttpURLConnection httpURLConnection = this.connection;
        long j = -1;
        if (httpURLConnection == null) {
            return -1;
        }
        String headerField = httpURLConnection.getHeaderField("Cache-Control");
        if (!TextUtils.isEmpty(headerField)) {
            StringTokenizer stringTokenizer = new StringTokenizer(headerField, ",");
            while (true) {
                if (!stringTokenizer.hasMoreTokens()) {
                    break;
                }
                String lowerCase = stringTokenizer.nextToken().trim().toLowerCase();
                if (lowerCase.startsWith("max-age")) {
                    int indexOf = lowerCase.indexOf(61);
                    if (indexOf > 0) {
                        try {
                            long parseLong = Long.parseLong(lowerCase.substring(indexOf + 1).trim());
                            if (parseLong > 0) {
                                j = System.currentTimeMillis() + (parseLong * 1000);
                            }
                        } catch (Throwable th) {
                            LogUtil.e(th.getMessage(), th);
                        }
                    }
                }
            }
        }
        if (j <= 0) {
            j = this.connection.getExpiration();
        }
        if (j <= 0 && this.params.getCacheMaxAge() > 0) {
            j = System.currentTimeMillis() + this.params.getCacheMaxAge();
        }
        if (j <= 0) {
            return Long.MAX_VALUE;
        }
        return j;
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public long getHeaderFieldDate(String str, long j) {
        HttpURLConnection httpURLConnection = this.connection;
        return httpURLConnection == null ? j : httpURLConnection.getHeaderFieldDate(str, j);
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public InputStream getInputStream() {
        HttpURLConnection httpURLConnection = this.connection;
        if (httpURLConnection != null && this.inputStream == null) {
            this.inputStream = httpURLConnection.getResponseCode() >= 400 ? this.connection.getErrorStream() : this.connection.getInputStream();
        }
        return this.inputStream;
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public long getLastModified() {
        return getHeaderFieldDate("Last-Modified", System.currentTimeMillis());
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public String getRequestUri() {
        URL url;
        String str = this.queryUrl;
        HttpURLConnection httpURLConnection = this.connection;
        return (httpURLConnection == null || (url = httpURLConnection.getURL()) == null) ? str : url.toString();
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public int getResponseCode() {
        return this.connection != null ? this.responseCode : getInputStream() != null ? 200 : 404;
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public String getResponseHeader(String str) {
        HttpURLConnection httpURLConnection = this.connection;
        if (httpURLConnection == null) {
            return null;
        }
        return httpURLConnection.getHeaderField(str);
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public Map<String, List<String>> getResponseHeaders() {
        HttpURLConnection httpURLConnection = this.connection;
        if (httpURLConnection == null) {
            return null;
        }
        return httpURLConnection.getHeaderFields();
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public String getResponseMessage() {
        HttpURLConnection httpURLConnection = this.connection;
        if (httpURLConnection != null) {
            return URLDecoder.decode(httpURLConnection.getResponseMessage(), this.params.getCharset());
        }
        return null;
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public boolean isLoading() {
        return this.isLoading;
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public Object loadResult() {
        this.isLoading = true;
        return super.loadResult();
    }

    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public Object loadResultFromCache() {
        this.isLoading = true;
        DiskCacheEntity diskCacheEntity = LruDiskCache.getDiskCache(this.params.getCacheDirName()).setMaxSize(this.params.getCacheSize()).get(getCacheKey());
        if (diskCacheEntity == null) {
            return null;
        }
        if (HttpMethod.permitsCache(this.params.getMethod())) {
            Date lastModify = diskCacheEntity.getLastModify();
            if (lastModify.getTime() > 0) {
                this.params.setHeader("If-Modified-Since", toGMTString(lastModify));
            }
            String etag = diskCacheEntity.getEtag();
            if (!TextUtils.isEmpty(etag)) {
                this.params.setHeader("If-None-Match", etag);
            }
        }
        return this.loader.loadFromCache(diskCacheEntity);
    }

    /* JADX WARNING: Removed duplicated region for block: B:71:0x016f  */
    /* JADX WARNING: Removed duplicated region for block: B:72:0x0179  */
    @Override // com.duoyou.task.sdk.xutils.http.request.UriRequest
    public void sendRequest() {
        RequestBody requestBody;
        boolean z = false;
        this.isLoading = false;
        this.responseCode = 0;
        URL url = new URL(this.queryUrl);
        Proxy proxy = this.params.getProxy();
        this.connection = (HttpURLConnection) (proxy != null ? url.openConnection(proxy) : 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 sslSocketFactory = this.params.getSslSocketFactory();
            if (sslSocketFactory != null) {
                ((HttpsURLConnection) this.connection).setSSLSocketFactory(sslSocketFactory);
            }
            HostnameVerifier hostnameVerifier = this.params.getHostnameVerifier();
            if (hostnameVerifier != null) {
                ((HttpsURLConnection) this.connection).setHostnameVerifier(hostnameVerifier);
            }
        }
        if (this.params.isUseCookie()) {
            try {
                List<String> list = COOKIE_MANAGER.get(url.toURI(), new HashMap(0)).get("Cookie");
                if (list != null) {
                    this.connection.setRequestProperty("Cookie", TextUtils.join(";", list));
                }
            } catch (Throwable th) {
                LogUtil.e(th.getMessage(), th);
            }
        }
        List<BaseParams.Header> headers = this.params.getHeaders();
        if (headers != null) {
            for (BaseParams.Header header : headers) {
                String str = header.key;
                String valueStrOrNull = header.getValueStrOrNull();
                if (!TextUtils.isEmpty(str)) {
                    if (header.setHeader) {
                        this.connection.setRequestProperty(str, valueStrOrNull);
                    } else {
                        this.connection.addRequestProperty(str, valueStrOrNull);
                    }
                }
            }
        }
        ResponseParser responseParser = this.responseParser;
        if (responseParser != null) {
            responseParser.beforeRequest(this);
        }
        RequestInterceptListener requestInterceptListener = this.requestInterceptListener;
        if (requestInterceptListener != null) {
            requestInterceptListener.beforeRequest(this);
        }
        HttpMethod method = this.params.getMethod();
        try {
            this.connection.setRequestMethod(method.toString());
        } catch (ProtocolException e) {
            Field declaredField = HttpURLConnection.class.getDeclaredField("method");
            declaredField.setAccessible(true);
            declaredField.set(this.connection, method.toString());
        }
        if (HttpMethod.permitsRequestBody(method) && (requestBody = this.params.getRequestBody()) != null) {
            if (requestBody instanceof ProgressBody) {
                ((ProgressBody) requestBody).setProgressHandler(this.progressHandler);
            }
            String contentType = requestBody.getContentType();
            if (!TextUtils.isEmpty(contentType)) {
                this.connection.setRequestProperty("Content-Type", contentType);
            }
            long contentLength = requestBody.getContentLength();
            if (contentLength >= 0) {
                if (contentLength < 2147483647L) {
                    this.connection.setFixedLengthStreamingMode((int) contentLength);
                } else if (Build.VERSION.SDK_INT >= 19) {
                    this.connection.setFixedLengthStreamingMode(contentLength);
                }
                if (!z) {
                    this.connection.setRequestProperty("Transfer-Encoding", "chunked");
                } else {
                    this.connection.setRequestProperty("Content-Length", String.valueOf(contentLength));
                }
                this.connection.setDoOutput(true);
                requestBody.writeTo(this.connection.getOutputStream());
            }
            this.connection.setChunkedStreamingMode(262144);
            z = true;
            if (!z) {
            }
            this.connection.setDoOutput(true);
            requestBody.writeTo(this.connection.getOutputStream());
        }
        if (this.params.isUseCookie()) {
            try {
                Map<String, List<String>> headerFields = this.connection.getHeaderFields();
                if (headerFields != null) {
                    COOKIE_MANAGER.put(url.toURI(), headerFields);
                }
            } catch (Throwable th2) {
                LogUtil.e(th2.getMessage(), th2);
            }
        }
        this.responseCode = this.connection.getResponseCode();
        ResponseParser responseParser2 = this.responseParser;
        if (responseParser2 != null) {
            responseParser2.afterRequest(this);
        }
        RequestInterceptListener requestInterceptListener2 = this.requestInterceptListener;
        if (requestInterceptListener2 != null) {
            requestInterceptListener2.afterRequest(this);
        }
        int i = this.responseCode;
        if (i == 204 || i == 205) {
            throw new HttpException(this.responseCode, getResponseMessage());
        } else if (i < 300) {
            this.isLoading = true;
            return;
        } else {
            HttpException httpException = new HttpException(this.responseCode, getResponseMessage());
            try {
                httpException.setResult(IOUtil.readStr(getInputStream(), this.params.getCharset()));
            } catch (Throwable th3) {
                LogUtil.w(th3.getMessage(), th3);
            }
            LogUtil.e(httpException.toString() + ", url: " + this.queryUrl);
            throw httpException;
        }
    }
}