我写了一个Java客户端,它可以http
毫无问题地执行GET请求。现在,我想修改此客户端以执行https
GET请求。
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);
...
我期待一个简单的修改,例如使用HttpsGet
代替,HttpGet
但是没有,没有HttpsGet
可用的类。
修改此方法以处理https
GET请求的最简单方法是什么?
我开发了一种解决方案,看起来比这里发布的解决方案更容易
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句