簡體   English   中英

HttpURLConnection 忽略代理

[英]HttpURLConnection ignores proxy

Android 6.0 - 11.0。
CompileSdkVersion 30
minSdkVersion 23

HttpURLConnection 忽略代理 - 當指定一個不存在的地址時,它不會發誓。
我需要在編譯應用程序后,應用程序可以通過代理發送請求。
嘗試了以下內容:

System.setProperty("http.proxyHost", "host");
System.setProperty("http.proxyPort", "port_number");


System.setProperty("http.proxyUser", "user");
System.setProperty("http.proxyPassword", "password");

Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("***.***.***.***", 1111));
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(proxy);

        connection.connect();

我的代碼:

String getText(String url) throws IOException {


        Properties systemSettings = System.getProperties();
        systemSettings.put("https.proxyHost","***.***.***.***");
        systemSettings.put("https.proxyPort", "1490");
        systemSettings.put("https.proxyUsername", "user");
        systemSettings.put("https.proxyPassword", "pass");

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

        connection.connect();

        int responseCode = connection.getResponseCode();
        InputStream inputStream;
        if (200 <= responseCode && responseCode <= 299) {
            inputStream = connection.getInputStream();
        } else {
            inputStream = connection.getErrorStream();
        }

        BufferedReader in1 = new BufferedReader(
                new InputStreamReader(
                        inputStream));

        StringBuilder response = new StringBuilder();
        String currentLine;

        while ((currentLine = in1.readLine()) != null)
            response.append(currentLine);

        in1.close();

        return response.toString();
    }

使用它時,頁面根本不會加載:

 Authenticator authenticator = new Authenticator() {

        public PasswordAuthentication getPasswordAuthentication() {
            return (new PasswordAuthentication("user",
                    "password".toCharArray()));
        }
    };
    Authenticator.setDefault(authenticator);

請告訴我我做錯了什么。

我理解你的問題,如果你不需要使用代理,請使用此代碼

httpurlconnection.openconnection(Proxy.NO_PROXY)

或者如果使用代理

//Proxy instance, proxy ip = 10.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("10.0.0.1", 8080));
conn = new URL(urlString).openConnection(proxy);

如果你會得到響應 407

然后試試這段代碼

Authenticator authenticator = new Authenticator() {

    public PasswordAuthentication getPasswordAuthentication() {
        return (new PasswordAuthentication("user",
                "password".toCharArray()));
    }
};
Authenticator.setDefault(authenticator);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM