0

我可以使用 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 点,并且在到达 B 点时会给出异常。异常是 org.apache.http.conn.HttpHostConnectException: Connect to api.pushover.net:443 (api.pushover.net/108.59.13.232] failed: Connection timer out: connect.

我已经尝试使用代理,下面的代码高于其余部分

HttpHost proxy = new HttpHost("url",9090,"https");
httpClient = (HttpClient) HttpClientBuilder.create().setProxy(proxy).build();

这给了我一个 javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

然后我也尝试添加

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 台机器上,而无需对每台机器进行额外的手动配置。

有什么更好的我应该做的吗?

4

1 回答 1

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();
于 2016-05-16T14:42:12.043 回答