refactor: update http use XHR

Signed-off-by: MiaoWoo <admin@yumc.pw>
This commit is contained in:
MiaoWoo 2019-11-04 20:19:50 +08:00
parent 364463dc6a
commit 0012da9855
3 changed files with 43 additions and 154 deletions

View File

@ -27,6 +27,8 @@
"typescript": "^3.6.2" "typescript": "^3.6.2"
}, },
"dependencies": { "dependencies": {
"@ms/nashorn": "^0.1.0" "@ms/nashorn": "^0.1.0",
} "@ms/ployfill": "^0.1.0"
},
"gitHead": "562e2d00175c9d3a99c8b672aa07e6d92706a027"
} }

View File

@ -1,155 +1,41 @@
'use strict'; import '@ms/api'
/**
* HTTP
* Created by on 2017/2/9 0009.
*/
/*global Java, base, module, exports, require, __FILE__*/ export type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
var URL = Java.type("java.net.URL"); interface RequestConfig {
var UUID = Java.type("java.util.UUID"); url?: string;
var System = Java.type("java.lang.System"); method?: Method;
var Files = Java.type("java.nio.file.Files"); headers?: { [key: string]: string };
var Paths = Java.type("java.nio.file.Paths"); params?: { [key: string]: string };
var JavaString = Java.type("java.lang.String"); data?: any;
var SecureRandom = Java.type("java.security.SecureRandom");
var SSLContext = Java.type("javax.net.ssl.SSLContext");
var HttpsURLConnection = Java.type("javax.net.ssl.HttpsURLConnection");
var HostnameVerifier = Java.type("javax.net.ssl.HostnameVerifier");
var X509TrustManager = Java.type("javax.net.ssl.X509TrustManager");
// noinspection JSUnusedGlobalSymbols,JSUnusedLocalSymbols
var TrustAnyHostnameVerifier = new HostnameVerifier({
verify: function(hostname, session) {
return true;
}
});
var SSLSocketFactory = function initSSLSocketFactory() {
var sslContext = SSLContext.getInstance("TLS");
// noinspection JSUnusedGlobalSymbols
sslContext.init(null, [new X509TrustManager({
getAcceptedIssuers: function() {
return null;
},
checkClientTrusted: function(chain, authType) {
},
checkServerTrusted: function(chain, authType) {
}
})], new SecureRandom());
return sslContext.getSocketFactory();
}();
var config = {
Charset: 'UTF-8',
ConnectTimeout: 10000,
ReadTimeout: 10000,
Debug: false
};
function open(url, method, header) {
// conn.setRequestProperty
var conn = new URL(url).openConnection();
if (conn instanceof HttpsURLConnection) {
conn.setHostnameVerifier(TrustAnyHostnameVerifier);
conn.setSSLSocketFactory(SSLSocketFactory);
}
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(config.ConnectTimeout);
conn.setReadTimeout(config.ReadTimeout);
if (header) {
for (var key in header) {
// noinspection JSUnfilteredForInLoop
conn.setRequestProperty(key, header[key]);
}
}
return conn;
} }
function buildUrl(url, params) { function request(config: RequestConfig) {
if (params && Object.keys(params).length > 0) { // @ts-ignore
var queryStart = url.indexOf('?'); let xhr = new XMLHttpRequest();
if (queryStart === -1) { xhr.open(config.method, config.url, false);
url += '?'; for (const header in config.headers) {
xhr.setRequestHeader(header, config.headers[header]);
} }
return url += object2URLSearchParams(params); let future = xhr.send(config.data);
} return future.get();
return url;
} }
function request(config) { function _proxy(method: Method) {
var conn = open(buildUrl(config.url, config.query), config.method, config.header); return function(url: string, data?: any, config?: RequestConfig) {
try { return request({ url, method, data, ...config });
conn.connect();
var data = config.data;
if (data) {
var out = conn.getOutputStream();
if (typeof data === "object") {
var type = config.header['Content-Type'];
switch (type) {
case "application/x-www-form-urlencoded":
data = object2URLSearchParams(data);
break;
default:
data = JSON.stringify(data)
}
}
out.write(new JavaString(data).getBytes(config.Charset));
out.flush();
out.close();
}
return response(conn);
} finally {
conn.disconnect();
} }
} }
function response(conn) { export default {
var temp = Paths.get(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString()); get: _proxy('GET'),
Files.copy(conn.getInputStream(), temp); post: _proxy('POST'),
var result = new JavaString(Files.readAllBytes(temp), config.Charset); request
var tempFile = temp.toFile();
tempFile.delete() || tempFile.deleteOnExit();
return result;
} }
function object2URLSearchParams(params) {
var temp: string[] = [];
for (var key in params) {
temp.push(`${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
}
return temp.join('&')
}
var http = {
config: config,
request: request
};
['GET', 'DELETE', 'HEAD', 'OPTIONS'].forEach(function(method) {
http[method.toLowerCase()] = function __likeGet__(url, data, config = {}) {
return this.request({
...config,
url: url,
method: method,
query: data
});
}
});
['POST', 'PUT', 'PATCH'].forEach(function(method) {
http[method.toLowerCase()] = function __likePost__(url, data, config) {
return this.request({
...config,
url: url,
method: method,
data: data
});
}
});
export = http;

View File

@ -1,7 +1,7 @@
import '@ms/core' import '@ms/core'
/** /**
* *
* Created by on 2017/2/9 0009. * Created by MiaoWoo on 2017/2/9 0009.
*/ */
const JavaClass = Java.type('java.lang.Class'); const JavaClass = Java.type('java.lang.Class');
const JavaObject = Java.type('java.lang.Object') const JavaObject = Java.type('java.lang.Object')
@ -13,6 +13,7 @@ class Reflect {
private class: any private class: any
constructor(obj: any) { constructor(obj: any) {
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
if (obj instanceof JavaClass) { if (obj instanceof JavaClass) {
this.obj = null; this.obj = null;
this.class = obj; this.class = obj;
@ -112,17 +113,17 @@ function declaredConstructor(clazz, param) {
} }
function declaredField(clazz, name) { function declaredField(clazz, name) {
let clazzt = clazz; if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
let target = clazz;
let field = null; let field = null;
// noinspection JSUnresolvedVariable // noinspection JSUnresolvedVariable
while (clazzt !== JavaObject.class) { while (target !== JavaObject.class) {
try { try {
field = clazzt.getDeclaredField(name); field = target.getDeclaredField(name);
if (field !== null) { if (field !== null) { break; }
break;
}
} catch (e) { } catch (e) {
clazzt = clazzt.getSuperclass(); if (target === undefined) { break; }
target = target.getSuperclass();
} }
} }
if (field === null) { if (field === null) {