首页 > 解决方案 > nashorn,使用身份验证通过代理的http请求

问题描述

我正在尝试使用 nashorn (javascript) 通过代理执行 http/https 请求。

到目前为止,我收到此错误:

java.lang.RuntimeException: java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.1 407 Proxy Authentication Required"<br/>at jdk.nashorn.internal.runtime.ScriptRuntime.apply

这是我的代码,请让我知道我做错了什么。

var System = Java.type("java.lang.System");
var JAuthenticator = Java.type("java.net.Authenticator");
var ProxyAuthenticator = Java.extend(JAuthenticator);
var ProxyAuthenticator = (function() {
    var 
        ProxyAuthenticator = Java.extend(JAuthenticator),
        _getPasswordAuthentication = function() { 
            return new java.net.PasswordAuthentication("user", "pwd".split(''));
        };
    return function(u, p) {
        return new ProxyAuthenticator() {
            getPasswordAuthentication : _getPasswordAuthentication
        };
    };
})();
System.setProperty("proxySet", "true");
System.setProperty("http.proxyHost", "proxy1");
System.setProperty("http.proxyPort", "8080");
System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "pwd");
System.setProperty("https.proxyHost", "proxy1");
System.setProperty("https.proxyPort", "8080");
System.setProperty("https.proxyUser", "user");
System.setProperty("https.proxyPassword", "pwd");
System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "");
System.setProperty("jdk.http.auth.proxying.disabledSchemes","");
System.setProperty("jdk.https.auth.tunneling.disabledSchemes", "");
System.setProperty("jdk.https.auth.proxying.disabledSchemes","");

JAuthenticator.setDefault(new ProxyAuthenticator());

httpGet("https://google.com");
    
//functions
function httpGet(theUrl){

    var con = new java.net.URL(theUrl).openConnection();
    con.requestMethod = "GET";
    return asResponse(con);
}
function asResponse(con){
    var d = read(con.inputStream);
    return {data : d, statusCode : con.responseCode};
}
function read(inputStream){
    var inReader = new java.io.BufferedReader(new java.io.InputStreamReader(inputStream));
    var inputLine;
    var response = new java.lang.StringBuffer();
    while ((inputLine = inReader.readLine()) != null) {
           response.append(inputLine);
    }
    inReader.close();
    return response.toString();
}

非常感谢。

标签: javascriptjavaauthenticationproxynashorn

解决方案


推荐阅读