我写了一个 Java 客户端,它可以http毫无问题地执行GET 请求。现在我想修改这个客户端以执行httpsGET 请求。
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
private String executeGet(final String url, String proxy, int port)
throws IOException, RequestUnsuccesfulException, InvalidParameterException {
CloseableHttpClient httpclient = null;
String ret = "";
RequestConfig config;
try {
String hostname = extractHostname(url);
logger.info("Hostname {}", hostname);
HttpHost target = new HttpHost(hostname, 80, null);
HttpHost myProxy = new HttpHost(proxy, port, "http");
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(USERNAME, PASSWORD));
httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
config = RequestConfig.custom().setProxy(myProxy).build();
HttpGet request = new HttpGet(url);
request.setConfig(config);
CloseableHttpResponse response = httpclient.execute(target, request);
...
Run Code Online (Sandbox Code Playgroud)
我期待一个简单的修改,比如使用HttpsGet而不是HttpGet但不,没有HttpsGet可用的类。
修改此方法以处理httpsGET 请求的最简单方法是什么?
我开发了一个解决方案,看起来比这里发布的更容易
private String executeGet(final String https_url, final String proxyName, final int port) {
String ret = "";
URL url;
try {
HttpsURLConnection con;
url = new URL(https_url);
if (proxyName.isEmpty()) {
con = (HttpsURLConnection) url.openConnection();
} else {
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyName, port));
con = (HttpsURLConnection) url.openConnection(proxy);
Authenticator authenticator = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication(USERNAME, PASSWORD.toCharArray()));
}
};
Authenticator.setDefault(authenticator);
}
ret = getContent(con);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)