【问题标题】:http-post through proxy not working通过代理的http-post不起作用
【发布时间】:2016-09-09 20:11:31
【问题描述】:

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

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

【问题讨论】:

    标签: java apache proxy http-post pushover


    【解决方案1】:

    我已经用这个代码代替了开头的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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 2013-09-18
      • 1970-01-01
      相关资源
      最近更新 更多