正在查看: Vesuvius v228 应用的 OkHttpClientWrapper.java JAVA 源代码文件
本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。
正在查看: Vesuvius v228 应用的 OkHttpClientWrapper.java JAVA 源代码文件
本页面展示 JAVA 反编译生成的源代码文件,支持语法高亮显示。 仅供安全研究与技术分析使用,严禁用于任何非法用途。请遵守相关法律法规。
package anywheresoftware.b4h.okhttp;
import anywheresoftware.b4a.BA;
import anywheresoftware.b4a.keywords.Common;
import anywheresoftware.b4a.objects.collections.Map;
import anywheresoftware.b4a.objects.streams.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CookieManager;
import java.net.CookiePolicy;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.JavaNetCookieJar;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;
import okhttp3.internal.Util;
import okhttp3.internal.http.RequestLine;
import okio.BufferedSink;
import okio.Okio;
import okio.Source;
@BA.Version(1.5f)
@BA.ShortName("OkHttpClient")
public class OkHttpClientWrapper {
public OkHttpClient client;
private String eventName;
public void Initialize(String str) {
this.client = sharedInit(str).build();
}
public void InitializeAcceptAll(String str) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
OkHttpClient.Builder sharedInit = sharedInit(str);
sharedInit.hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String str2, SSLSession sSLSession) {
return true;
}
});
SSLContext sSLContext = SSLContext.getInstance("SSL");
sSLContext.init(null, new TrustManager[]{new NaiveTrustManager(null)}, new SecureRandom());
SSLSocketFactory socketFactory = sSLContext.getSocketFactory();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length == 1) {
TrustManager trustManager = trustManagers[0];
if (trustManager instanceof X509TrustManager) {
sharedInit.sslSocketFactory(socketFactory, (X509TrustManager) trustManager);
this.client = sharedInit.build();
return;
}
}
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
public OkHttpClient.Builder sharedInit(String str) {
OkHttpClient.Builder builder = new OkHttpClient.Builder();
this.eventName = str.toLowerCase(BA.cul);
setTimeout(builder, 30000);
CookieManager cookieManager = new CookieManager();
cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);
builder.cookieJar(new JavaNetCookieJar(cookieManager));
return builder;
}
public boolean IsInitialized() {
return this.client != null;
}
static void setTimeout(OkHttpClient.Builder builder, int i) {
long j = i;
builder.connectTimeout(j, TimeUnit.MILLISECONDS);
builder.writeTimeout(j, TimeUnit.MILLISECONDS);
builder.readTimeout(j, TimeUnit.MILLISECONDS);
}
public boolean Execute(BA ba, OkHttpRequest okHttpRequest, int i) throws IOException {
return ExecuteCredentials(ba, okHttpRequest, i, null, null);
}
public boolean ExecuteCredentials(BA ba, OkHttpRequest okHttpRequest, int i, String str, String str2) {
if (BA.isTaskRunning(this, i)) {
return false;
}
BA.submitRunnable(new ExecuteHelper(ba, okHttpRequest, i, str, str2), this, i);
return true;
}
public Response executeWithTimeout(Runnable runnable, OkHttpClient okHttpClient, Request request, BA ba, int i) throws IOException {
return okHttpClient.newCall(request).execute();
}
class ExecuteHelper implements Runnable {
private OkHttpRequest HttpRequest;
private String Password;
private int TaskId;
private String UserName;
private BA ba;
public ExecuteHelper(BA ba, OkHttpRequest okHttpRequest, int i, String str, String str2) {
this.ba = ba;
this.HttpRequest = okHttpRequest;
this.TaskId = i;
this.UserName = str;
this.Password = str2;
}
@Override
public void run() {
String exc;
int i;
OkHttpResponse okHttpResponse = new OkHttpResponse();
okHttpResponse.innerInitialize(OkHttpClientWrapper.this);
Response response = null;
try {
OkHttpClient.Builder newBuilder = OkHttpClientWrapper.this.client.newBuilder();
OkHttpClientWrapper.setTimeout(newBuilder, this.HttpRequest.timeout);
Request build = this.HttpRequest.builder.build();
boolean z = ((build.body() instanceof PostPayload) && ((PostPayload) build.body()).data == null) ? false : true;
String str = this.UserName;
if (str != null && str.length() > 0) {
newBuilder.authenticator(new B4AAuthenticator(this.UserName, this.Password));
if ((build.body() instanceof PostPayload) && !z) {
build = build.newBuilder().header("Authorization", Credentials.basic(this.UserName, this.Password)).build();
}
}
newBuilder.retryOnConnectionFailure(z);
Response executeWithTimeout = OkHttpClientWrapper.this.executeWithTimeout(this, newBuilder.build(), build, this.ba, this.TaskId);
if (executeWithTimeout == null) {
return;
}
okHttpResponse.response = executeWithTimeout;
if (!executeWithTimeout.isSuccessful()) {
throw new Exception();
}
BA ba = this.ba;
OkHttpClient okHttpClient = OkHttpClientWrapper.this.client;
OkHttpClientWrapper okHttpClientWrapper = OkHttpClientWrapper.this;
ba.raiseEventFromDifferentThread(okHttpClient, okHttpClientWrapper, this.TaskId, String.valueOf(okHttpClientWrapper.eventName) + "_responsesuccess", true, new Object[]{okHttpResponse, Integer.valueOf(this.TaskId)});
} catch (Exception e) {
if (0 != 0) {
i = response.code();
exc = response.message();
if (exc == null) {
exc = "";
}
} else {
e.printStackTrace();
exc = e.toString();
i = -1;
}
if (0 != 0) {
try {
okHttpResponse.errorMessage = response.body().string();
} catch (Exception e2) {
e2.printStackTrace();
}
}
BA ba2 = this.ba;
OkHttpClient okHttpClient2 = OkHttpClientWrapper.this.client;
OkHttpClientWrapper okHttpClientWrapper2 = OkHttpClientWrapper.this;
ba2.raiseEventFromDifferentThread(okHttpClient2, okHttpClientWrapper2, this.TaskId, String.valueOf(okHttpClientWrapper2.eventName) + "_responseerror", false, new Object[]{okHttpResponse, exc, Integer.valueOf(i), Integer.valueOf(this.TaskId)});
}
}
}
public static class B4AAuthenticator implements Authenticator {
private static final char[] HEXADECIMAL = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static Pattern ptDigest;
public final String password;
public final String username;
public B4AAuthenticator(String str, String str2) {
this.username = str;
this.password = str2;
}
public Request authenticate(Route route, Response response) throws IOException {
String basic;
if (responseCount(response) >= 3) {
return null;
}
String header = response.header("WWW-Authenticate");
if (header == null) {
header = "";
}
if (header.toLowerCase(BA.cul).contains("digest")) {
basic = handleDigest(response, header);
} else {
basic = Credentials.basic(this.username, this.password);
if (basic.equals(response.request().header("Authorization"))) {
return null;
}
}
return response.request().newBuilder().header("Authorization", basic).build();
}
private String handleDigest(Response response, String str) throws IOException {
String str2;
String str3;
boolean z;
Request request = response.request();
String method = request.method();
String requestPath = RequestLine.INSTANCE.requestPath(request.url());
if (ptDigest == null) {
ptDigest = Pattern.compile("(\\w+)=\\\"([^\"]+)\\\"");
}
Matcher matcher = ptDigest.matcher(str);
HashMap hashMap = new HashMap();
while (matcher.find()) {
hashMap.put(matcher.group(1), matcher.group(2));
}
String str4 = (String) hashMap.get("nonce");
String str5 = (String) hashMap.get("realm");
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
String encode = encode(messageDigest.digest((this.username + ":" + str5 + ":" + this.password).getBytes("ISO-8859-1")));
StringBuilder sb = new StringBuilder(String.valueOf(method));
sb.append(":");
sb.append(requestPath);
String sb2 = sb.toString();
boolean contains = str.contains("qop") ^ true;
String encode2 = encode(messageDigest.digest(sb2.getBytes("ASCII")));
if (!contains) {
String encode3 = encode(messageDigest.digest(Long.toString(System.currentTimeMillis()).getBytes("ASCII")));
str2 = encode + ':' + str4 + ":00000001:" + encode3 + ":auth:" + encode2;
str3 = encode3;
} else {
str2 = encode + ':' + str4 + ':' + encode2;
str3 = null;
}
String encode4 = encode(messageDigest.digest(str2.getBytes("ASCII")));
StringBuilder sb3 = new StringBuilder("Digest ");
sb3.append(param("username", this.username, true));
sb3.append(",");
sb3.append(param("realm", str5, true));
sb3.append(",");
sb3.append(param("nonce", str4, true));
sb3.append(",");
sb3.append(param("uri", requestPath, true));
sb3.append(",");
if (contains) {
z = true;
} else {
sb3.append(param("qop", "auth", false));
sb3.append(",");
sb3.append(param("nc", "00000001", false));
sb3.append(",");
z = true;
sb3.append(param("cnonce", str3, true));
sb3.append(",");
}
sb3.append(param("response", encode4, z));
String str6 = (String) hashMap.get("opaque");
if (str6 != null) {
sb3.append(",");
sb3.append(param("opaque", str6, z));
}
return sb3.toString();
} catch (NoSuchAlgorithmException unused) {
throw new RuntimeException();
}
}
private String param(String str, String str2, boolean z) {
StringBuilder sb = new StringBuilder(String.valueOf(str));
sb.append("=");
String str3 = Common.QUOTE;
sb.append(z ? Common.QUOTE : "");
sb.append(str2);
if (!z) {
str3 = "";
}
sb.append(str3);
return sb.toString();
}
private static String encode(byte[] bArr) {
if (bArr.length != 16) {
return null;
}
char[] cArr = new char[32];
for (int i = 0; i < 16; i++) {
byte b = bArr[i];
int i2 = i * 2;
char[] cArr2 = HEXADECIMAL;
cArr[i2] = cArr2[(b & 240) >> 4];
cArr[i2 + 1] = cArr2[b & 15];
}
return new String(cArr);
}
private int responseCount(Response response) {
int i = 1;
while (true) {
response = response.priorResponse();
if (response == null) {
return i;
}
i++;
}
}
}
@BA.ShortName("OkHttpRequest")
public static class OkHttpRequest {
public Request.Builder builder;
public PostPayload pp;
int timeout = 30000;
public void InitializeGet(String str) {
this.builder = new Request.Builder().url(str).get();
}
public void InitializeHead(String str) {
this.builder = new Request.Builder().url(str).head();
}
public void InitializeDelete(String str) {
this.builder = new Request.Builder().url(str).delete();
}
public void InitializeDelete2(String str, byte[] bArr) {
this.pp = PostPayload.createFromArray(bArr);
this.builder = new Request.Builder().url(str).delete(this.pp);
}
public void InitializePost(String str, InputStream inputStream, int i) {
this.pp = PostPayload.createFromStream(inputStream, i);
this.builder = new Request.Builder().url(str).post(this.pp);
}
public void InitializePost2(String str, byte[] bArr) {
this.pp = PostPayload.createFromArray(bArr);
this.builder = new Request.Builder().url(str).post(this.pp);
}
public void InitializePut(String str, InputStream inputStream, int i) {
this.pp = PostPayload.createFromStream(inputStream, i);
this.builder = new Request.Builder().url(str).put(this.pp);
}
public void InitializePut2(String str, byte[] bArr) {
this.pp = PostPayload.createFromArray(bArr);
this.builder = new Request.Builder().url(str).put(this.pp);
}
public void InitializePatch(String str, InputStream inputStream, int i) {
this.pp = PostPayload.createFromStream(inputStream, i);
this.builder = new Request.Builder().url(str).patch(this.pp);
}
public void InitializePatch2(String str, byte[] bArr) {
this.pp = PostPayload.createFromArray(bArr);
this.builder = new Request.Builder().url(str).patch(this.pp);
}
public void SetHeader(String str, String str2) {
this.builder.addHeader(str, str2);
}
public void RemoveHeaders(String str) {
this.builder.removeHeader(str);
}
public int getTimeout() {
return this.timeout;
}
public void setTimeout(int i) {
this.timeout = i;
}
public void SetContentType(String str) {
PostPayload postPayload = this.pp;
if (postPayload == null) {
throw new RuntimeException("Request does not support this method.");
}
postPayload.contentType = str;
}
public void SetContentEncoding(String str) {
this.builder.header("Content-Encoding", str);
}
}
public static class PostPayload extends RequestBody {
public byte[] data;
private Source source;
public String contentType = "application/x-www-form-urlencoded";
private long contentLength = -1;
public static PostPayload createFromStream(InputStream inputStream, int i) {
PostPayload postPayload = new PostPayload();
postPayload.source = Okio.source(inputStream);
postPayload.contentLength = i;
return postPayload;
}
public static PostPayload createFromArray(byte[] bArr) {
PostPayload postPayload = new PostPayload();
postPayload.data = bArr;
return postPayload;
}
public MediaType contentType() {
return MediaType.parse(this.contentType);
}
public long contentLength() throws IOException {
if (this.data != null) {
return r0.length;
}
return this.contentLength;
}
public void writeTo(BufferedSink bufferedSink) throws IOException {
byte[] bArr = this.data;
if (bArr != null) {
bufferedSink.write(bArr);
} else {
bufferedSink.write(this.source, this.contentLength);
}
}
}
@BA.ShortName("OkHttpResponse")
public static class OkHttpResponse {
String errorMessage = "";
private OkHttpClientWrapper parent;
public Response response;
public void innerInitialize(OkHttpClientWrapper okHttpClientWrapper) {
this.parent = okHttpClientWrapper;
}
public Map GetHeaders() {
return convertHeaders(this.response.headers().toMultimap());
}
public String getContentType() {
return this.response.header("Content-Type", "");
}
public String getContentEncoding() {
return this.response.header("Content-Encoding", "");
}
public String getErrorResponse() {
return this.errorMessage;
}
public long getContentLength() throws IOException {
return this.response.body().contentLength();
}
static Map convertHeaders(java.util.Map<String, List<String>> map) {
Map map2 = new Map();
map2.Initialize();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
map2.Put(entry.getKey(), entry.getValue());
}
return map2;
}
public int getStatusCode() {
Response response = this.response;
if (response == null) {
return -1;
}
return response.code();
}
public void Release() throws IOException {
Response response = this.response;
if (response == null || response.body() == null) {
return;
}
Util.closeQuietly(this.response.body().source());
}
public boolean GetAsynchronously(final BA ba, final String str, final OutputStream outputStream, final boolean z, final int i) throws IOException {
if (BA.isTaskRunning(this.parent, i)) {
Release();
return false;
}
BA.submitRunnable(new Runnable() {
@Override
public void run() {
try {
File.Copy2(OkHttpResponse.this.response.body().byteStream(), outputStream);
if (z) {
outputStream.close();
}
BA ba2 = ba;
OkHttpResponse okHttpResponse = OkHttpResponse.this;
ba2.raiseEventFromDifferentThread(okHttpResponse, okHttpResponse.parent, i, String.valueOf(str.toLowerCase(BA.cul)) + "_streamfinish", true, new Object[]{true, Integer.valueOf(i)});
} catch (IOException e) {
ba.setLastException(e);
if (z) {
try {
outputStream.close();
} catch (IOException unused) {
}
}
BA ba3 = ba;
OkHttpResponse okHttpResponse2 = OkHttpResponse.this;
ba3.raiseEventFromDifferentThread(okHttpResponse2, okHttpResponse2.parent, i, String.valueOf(str.toLowerCase(BA.cul)) + "_streamfinish", true, new Object[]{false, Integer.valueOf(i)});
}
OkHttpResponse.this.response.body().close();
}
}, this.parent, i);
return true;
}
}
private static class NaiveTrustManager implements X509TrustManager {
@Override
public void checkClientTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
private NaiveTrustManager() {
}
NaiveTrustManager(NaiveTrustManager naiveTrustManager) {
this();
}
}
}