我可以使用Chrome浏览器访问https://pushover.net/,但是当我尝试使用java连接到api并发送数据时访问同一个网站时,它会失败。
这是我的代码
HttpClient httpClient = (HttpClient) HttpClientBuilder.create()/*.setProxy(proxy)*/.build();
HttpPost post = new HttpPost("https://api.pushover.net/1/messages.json");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("token", apiToken));
nvps.add(new BasicNameValuePair("user", userKey));
nvps.add(new BasicNameValuePair("message", message));
post.setEntity(new UrlEncodedFormEntity(nvps, Charset.defaultCharset()));
//point A
HttpResponse deviceResponse = httpClient.execute(post);
//point B
它到达A点,但是然后需要很长时间才能到达B点,并且当它发生时它会给出异常。 例外是 org.apache.http.conn.HttpHostConnectException:连接到api.pushover.net:443(api.pushover.net/108.59.13.232)失败:连接计时器输出:连接。
我尝试使用代理,其代码高于其余代码
HttpHost proxy = new HttpHost("url",9090,"https");
httpClient = (HttpClient) HttpClientBuilder.create().setProxy(proxy).build();
这给了我一个 javax.net.ssl.SSLHandshakeException:握手期间远程主机关闭连接
然后我也尝试添加
Authenticator.setDefault(
new Authenticator() {
@Override
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
authUser, authPassword.toCharArray());
}
}
);
System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);
但它给出了相同的SSLHandshakeException。
我已经看到了创建密钥库的事情,但这只能在我的机器上运行,我想要一些可以在代码中运行的东西,并允许我将这个应用程序部署到1000台机器上,而无需额外的手册配置每个。
我应该做的更好吗?
答案 0 :(得分:0)
我已使用此代码修改了它,而不是开头的httpClient
。
HttpHost proxy = new HttpHost(PROXY_URL, 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
AuthCache authCache = new BasicAuthCache();
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(new AuthScope(PROXY_URL, 8080, AuthScope.ANY_HOST, "ntlm"), new NTCredentials(authUser, authPassword, "",PROXY_DOMAIN));
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credsProvider);
context.setAuthCache(authCache);
httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setRoutePlanner(routePlanner).build();