Android 6.0 - 11.0.
СompileSdkVersion 30
minSdkVersion 23
HttpURLConnection ignores proxy - when specifying a non-existent address, it does not swear.
I need that after compiling the application, the application could send requests through proxy.
Tried the following:
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();
My code:
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();
}
When using this, page is not loaded at all:
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("user",
"password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
Please tell me what I do wrong.
what I understand your question, if you not need for using Proxy, use this code
httpurlconnection.openconnection(Proxy.NO_PROXY)
or if use 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);
if you will get response 407
then try this code
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("user",
"password".toCharArray()));
}
};
Authenticator.setDefault(authenticator);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.