package zj.xuitls.http.request; import android.os.Build; import android.text.TextUtils; import com.mbridge.msdk.foundation.download.Command; import java.io.IOException; 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; import zj.xuitls.cache.DiskCacheEntity; import zj.xuitls.cache.LruDiskCache; import zj.xuitls.common.util.IOUtil; import zj.xuitls.common.util.KeyValue; import zj.xuitls.common.util.LogUtil; import zj.xuitls.ex.HttpException; import zj.xuitls.http.BaseParams; import zj.xuitls.http.HttpMethod; import zj.xuitls.http.RequestParams; import zj.xuitls.http.body.ProgressBody; import zj.xuitls.http.body.RequestBody; import zj.xuitls.http.cookie.DbCookieStore; 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) throws Throwable { super(requestParams, type); } /* access modifiers changed from: protected */ @Override // zj.xuitls.http.request.UriRequest public String buildQueryUrl(RequestParams requestParams) throws IOException { 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 // zj.xuitls.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(); } /* JADX WARNING: Removed duplicated region for block: B:73:0x017d */ /* JADX WARNING: Removed duplicated region for block: B:74:0x0187 */ @Override // zj.xuitls.http.request.UriRequest public void sendRequest() throws Throwable { RequestBody requestBody; boolean z = false; this.isLoading = false; this.responseCode = 0; URL url = new URL(this.queryUrl); Proxy proxy = this.params.getProxy(); if (proxy != null) { this.connection = (HttpURLConnection) url.openConnection(proxy); } else { this.connection = (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 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); } } } } if (this.responseParser != null) { this.responseParser.beforeRequest(this); } if (this.requestInterceptListener != null) { this.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) { this.connection.setChunkedStreamingMode(262144); } else { if (contentLength < 2147483647L) { this.connection.setFixedLengthStreamingMode((int) contentLength); } else if (Build.VERSION.SDK_INT >= 19) { this.connection.setFixedLengthStreamingMode(contentLength); } else { this.connection.setChunkedStreamingMode(262144); } 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()); } 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(); if (this.responseParser != null) { this.responseParser.afterRequest(this); } if (this.requestInterceptListener != null) { this.requestInterceptListener.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; } } @Override // zj.xuitls.http.request.UriRequest public boolean isLoading() { return this.isLoading; } @Override // zj.xuitls.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; } @Override // zj.xuitls.http.request.UriRequest public Object loadResult() throws Throwable { this.isLoading = true; return super.loadResult(); } @Override // zj.xuitls.http.request.UriRequest public Object loadResultFromCache() throws Throwable { 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); } @Override // zj.xuitls.http.request.UriRequest public void clearCacheHeader() { this.params.setHeader("If-Modified-Since", null); this.params.setHeader("If-None-Match", null); } @Override // zj.xuitls.http.request.UriRequest public InputStream getInputStream() throws IOException { 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 // zj.xuitls.http.request.UriRequest, java.io.Closeable, java.lang.AutoCloseable public void close() throws IOException { InputStream inputStream2 = this.inputStream; if (inputStream2 != null) { IOUtil.closeQuietly(inputStream2); this.inputStream = null; } HttpURLConnection httpURLConnection = this.connection; if (httpURLConnection != null) { httpURLConnection.disconnect(); } } @Override // zj.xuitls.http.request.UriRequest public long getContentLength() { HttpURLConnection httpURLConnection = this.connection; long j = -1; if (httpURLConnection != null) { try { String headerField = httpURLConnection.getHeaderField("content-length"); if (headerField != null) { j = Long.parseLong(headerField); } } catch (Throwable th) { LogUtil.e(th.getMessage(), th); } } if (j >= 1) { return j; } try { return (long) getInputStream().available(); } catch (Throwable unused) { return j; } } @Override // zj.xuitls.http.request.UriRequest public int getResponseCode() throws IOException { if (this.connection != null) { return this.responseCode; } return getInputStream() != null ? 200 : 404; } @Override // zj.xuitls.http.request.UriRequest public String getResponseMessage() throws IOException { HttpURLConnection httpURLConnection = this.connection; if (httpURLConnection != null) { return URLDecoder.decode(httpURLConnection.getResponseMessage(), this.params.getCharset()); } return null; } @Override // zj.xuitls.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 // zj.xuitls.http.request.UriRequest public long getLastModified() { return getHeaderFieldDate("Last-Modified", System.currentTimeMillis()); } @Override // zj.xuitls.http.request.UriRequest public String getETag() { HttpURLConnection httpURLConnection = this.connection; if (httpURLConnection == null) { return null; } return httpURLConnection.getHeaderField(Command.HTTP_HEADER_ETAG); } @Override // zj.xuitls.http.request.UriRequest public String getResponseHeader(String str) { HttpURLConnection httpURLConnection = this.connection; if (httpURLConnection == null) { return null; } return httpURLConnection.getHeaderField(str); } @Override // zj.xuitls.http.request.UriRequest public Map<String, List<String>> getResponseHeaders() { HttpURLConnection httpURLConnection = this.connection; if (httpURLConnection == null) { return null; } return httpURLConnection.getHeaderFields(); } @Override // zj.xuitls.http.request.UriRequest public long getHeaderFieldDate(String str, long j) { HttpURLConnection httpURLConnection = this.connection; if (httpURLConnection == null) { return j; } return httpURLConnection.getHeaderFieldDate(str, j); } 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); } }