Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7929d88

Browse files
committed
Support HTTP_PROXY & HTTPS_PROXY
1 parent 050f08a commit 7929d88

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

aliyun-java-sdk-core/src/main/java/com/aliyuncs/http/HttpRequest.java

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ public class HttpRequest {
3939
protected static final String CONTENT_LENGTH = "Content-Length";
4040

4141
private String url = null;
42+
private String proxyAuth = null;
4243
private MethodType method = null;
4344
protected FormatType httpContentType = null;
4445
protected byte[] httpContent = null;
@@ -178,14 +179,20 @@ public HttpURLConnection buildHttpConnection() throws IOException, GeneralSecuri
178179
HttpURLConnection httpConn = null;
179180
if (url.getProtocol().equalsIgnoreCase("https")) {
180181
if (sslSocketFactory != null) {
181-
HttpsURLConnection httpsConn = (HttpsURLConnection)url.openConnection();
182+
Proxy proxy = getProxy("HTTPS_PROXY");
183+
HttpsURLConnection httpsConn = (HttpsURLConnection)url.openConnection(proxy);
182184
httpsConn.setSSLSocketFactory(sslSocketFactory);
183185
httpConn = httpsConn;
184186
}
185187
}
186188

187189
if (httpConn == null) {
188-
httpConn = (HttpURLConnection)url.openConnection();
190+
Proxy proxy = getProxy("HTTP_PROXY");
191+
httpConn = (HttpURLConnection)url.openConnection(proxy);
192+
}
193+
194+
if (this.proxyAuth != null) {
195+
httpConn.setRequestProperty("Proxy-Authorization", proxyAuth);
189196
}
190197

191198
httpConn.setRequestMethod(this.method.toString());
@@ -231,6 +238,26 @@ private String getContentTypeValue(FormatType contentType, String encoding) {
231238
return null;
232239
}
233240

241+
private Proxy getProxy(String env) {
242+
Proxy proxy = Proxy.NO_PROXY;
243+
String httpProxy = System.getenv(env);
244+
if (httpProxy != null) {
245+
URL proxyUrl = new URL(httpProxy);
246+
String userInfo = proxyUrl.getUserInfo();
247+
if (userInfo != null) {
248+
this.proxyAuth = "Basic " + Base64.encode(userInfo);
249+
}
250+
String hostname = proxyUrl.getHost();
251+
int port = proxyUrl.getPort();
252+
if (port == -1) {
253+
port = proxyUrl.getDefaultPort();
254+
}
255+
SocketAddress addr = new InetSocketAddress(hostname, port);
256+
proxy = new Proxy(Proxy.Type.HTTP, addr);
257+
}
258+
return proxy;
259+
}
260+
234261
public SSLSocketFactory getSslSocketFactory() {
235262
return sslSocketFactory;
236263
}

0 commit comments

Comments
 (0)