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"
},
"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';
/**
* HTTP
* Created by on 2017/2/9 0009.
*/
import '@ms/api'
/*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");
var UUID = Java.type("java.util.UUID");
var System = Java.type("java.lang.System");
var Files = Java.type("java.nio.file.Files");
var Paths = Java.type("java.nio.file.Paths");
var JavaString = Java.type("java.lang.String");
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;
interface RequestConfig {
url?: string;
method?: Method;
headers?: { [key: string]: string };
params?: { [key: string]: string };
data?: any;
}
function buildUrl(url, params) {
if (params && Object.keys(params).length > 0) {
var queryStart = url.indexOf('?');
if (queryStart === -1) {
url += '?';
}
return url += object2URLSearchParams(params);
function request(config: RequestConfig) {
// @ts-ignore
let xhr = new XMLHttpRequest();
xhr.open(config.method, config.url, false);
for (const header in config.headers) {
xhr.setRequestHeader(header, config.headers[header]);
}
return url;
let future = xhr.send(config.data);
return future.get();
}
function request(config) {
var conn = open(buildUrl(config.url, config.query), config.method, config.header);
try {
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 _proxy(method: Method) {
return function(url: string, data?: any, config?: RequestConfig) {
return request({ url, method, data, ...config });
}
}
function response(conn) {
var temp = Paths.get(System.getProperty("java.io.tmpdir"), UUID.randomUUID().toString());
Files.copy(conn.getInputStream(), temp);
var result = new JavaString(Files.readAllBytes(temp), config.Charset);
var tempFile = temp.toFile();
tempFile.delete() || tempFile.deleteOnExit();
return result;
export default {
get: _proxy('GET'),
post: _proxy('POST'),
request
}
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'
/**
*
* Created by on 2017/2/9 0009.
* Created by MiaoWoo on 2017/2/9 0009.
*/
const JavaClass = Java.type('java.lang.Class');
const JavaObject = Java.type('java.lang.Object')
@ -13,6 +13,7 @@ class Reflect {
private class: any
constructor(obj: any) {
// if (obj === undefined || obj === null) { throw Error(`reflect object can't be ${obj}!`) }
if (obj instanceof JavaClass) {
this.obj = null;
this.class = obj;
@ -112,17 +113,17 @@ function declaredConstructor(clazz, param) {
}
function declaredField(clazz, name) {
let clazzt = clazz;
if (!clazz) { throw Error(`target class can't be ${clazz}!`) }
let target = clazz;
let field = null;
// noinspection JSUnresolvedVariable
while (clazzt !== JavaObject.class) {
while (target !== JavaObject.class) {
try {
field = clazzt.getDeclaredField(name);
if (field !== null) {
break;
}
field = target.getDeclaredField(name);
if (field !== null) { break; }
} catch (e) {
clazzt = clazzt.getSuperclass();
if (target === undefined) { break; }
target = target.getSuperclass();
}
}
if (field === null) {