f1wade f1wade - 1 year ago 118
Java Question

http-post through proxy not working

I can get to https://pushover.net/ using chrome browser, but when i try to get to the same website using java to connect to the api and send data it fails.

this is my code

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

it gets to point A, but then takes ages to get to point B and it gives an exception when it does.
The Exception is
org.apache.http.conn.HttpHostConnectException: Connect to api.pushover.net:443 (api.pushover.net/] failed: Connection timer out: connect.

I have tried using a proxy with the below code above the rest

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

This gives me a
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake

I then also tried adding

new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
authUser, authPassword.toCharArray());

System.setProperty("http.proxyUser", authUser);
System.setProperty("http.proxyPassword", authPassword);

but it gives the same SSLHandshakeException.

I have seen things on creating keystores, but that will only work on my machine, I want something that will work in code and allow me to deploy this app to 1000's of machines, without having to do extra manual config to each.

Is there anything Better i should be doing?


I have fixed it with this code in place of the httpClient at the beginning.

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();

httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).setRoutePlanner(routePlanner).build();