我正在尝试通过JAVA打开需要用户名和密码的网页:
page I am trying to acces

这是我复制的引用为from this site的代码:

    public static void main(String[] args) {

    try {
        String webPage = "https://reports.tradenetworks.com/ReportServer_DISTRIBUTORRS?%2fDealing&rs:Command=ListChildren";
        String name = "Tradenetworks\\USER";
        String password = "PASS";
        String authString = name + ":" + password;
        System.out.println("auth string: " + authString);
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        System.out.println("Base64 encoded auth string:" + authStringEnc);

        URL url = new URL(webPage);
        URLConnection urlConnection = url.openConnection();
        urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        InputStream is = urlConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);

        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();

        System.out.println("*** BEGIN ***");
        System.out.println(result);
        System.out.println("*** END ***");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}


但是我从eclipse中得到了这个错误:

java.io.IOException: Authentication failure
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(Unknown Source)
at ConnectToUrlUsingBasicAuthentication.main(ConnectToUrlUsingBasicAuthentication.java:27)

最佳答案

我认为问题出在username带有斜杠(\\)的字符串中。 URL编码为%5C%5C时,这些字符看起来像这样。因此,您应该尝试String name = "Tradenetworks%5C%5CUSER";

希望有帮助!

10-08 19:29