HttpClient 4.5.2 Proxy setting - java

I need to call third party web service via proxy.
I only have information below:
- Third party https IP & Port
- Proxy http IP & Port
May I know I need credential : username & Password for the Proxy?
Part of my code below:-
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
DefaultProxyRoutePlanner routePlanner = new
DefaultProxyRoutePlanner(proxy);
CloseableHttpClient httpclient = HttpClients.custom()
.setRoutePlanner(routePlanner)
.build();
RequestConfig config =RequestConfig.custom().setProxy(proxy).build();
HttpPost httppost = new HttpPost(queryUrl);
httppost.setConfig(config);
CloseableHttpResponse httpResponse = httpclient.execute(httppost);
Unfortunately, Proxy server reponse me "Access denied. Authentication is required."
Any idea for this problem?

Related

Getting org.apache.http.client.ClientProtocolException

I'm using apache http client library to post a maltipart request on some secure(https) server
httpclient-4.5.13.jar, httpcore-4.4.13.jar, httpmime-4.4.1.jar
below is the sample code:
//creating HttpPost
HttpPost httppost = new HttpPost("some https://url");
httppost.addHeader("Content-Type", "multipart/form-data");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("channel_id", String.valueOf(pushNotificationRequest.getChannelId()));
builder.addTextBody("input_type", pushNotificationRequest.getInputType());
builder.addBinaryBody("csv_file", new ByteArrayInputStream(pushNotificationRequest.getCsvFile()), ContentType.DEFAULT_BINARY, "my-File.csv");
httppost.setEntity(builder.build());
//configuration for disabling the SSL
CloseableHttpClient httpClient = HttpClients
.custom()
.setSSLContext(new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).useProtocol("TLSv1.2").build())
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
//exicuting the httppost
httpClient.execute(httppost);
but in above configuration I'm getting a wired issue when I freshly start the tomcat server (as above code in a part of web-app) and when this code is executed I'm able to connect to server which I'm posting the my request and after second attempt onwards I'm getting a exception
as:
[ org.apache.http.client.ClientProtocolException ] null
org.apache.http.client.ClientProtocolException
I'm not able to understand why it's working when server freshly started and getting exception after subsequent call.
Any help is greatly appreciated.

http component can't connect to proxy

I'm trying to connect to a website through a proxy, but I'm getting an error
Error Code: 407 Proxy Authentication Required. Forefront TMG requires authorization to fulfill the request. Access to the Web Proxy filter is denied. (12209)
My code is very close to the example that apache provides, https://hc.apache.org/httpcomponents-client-ga/examples.html (see the proxy authentication example). I'm definitely doing something wrong with authentication, but...what?
HttpHost proxy = new HttpHost("http-proxy", 80);
HttpHost target = new HttpHost(url, 80);
CredentialsProvider credsProvider = new BasicCredentialsProvider();
credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user,password));
try (CloseableHttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(new SystemDefaultCredentialsProvider()).build()) {
RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
HttpGet httpget = new HttpGet("/basic-auth/user/passwd");
httpget.setConfig(config);
HttpResponse response = client.execute(target, httpget);
}
The problem seems to be that you are setting new SystemDefaultCredentialsProvider() when you are building the HTTP client. I guess you intention was to set credsProvider, to which you have just added proxy user and password.

PoolingHttpClientConnectionManager: How to do Https requests?

I'm currently trying to do multiple HttpGet requests at the same time with CloseableHttpClient.
I googled on how to do that and the answer was to use a PoolingHttpClientConnectionManager.
At this point I got this:
PoolingHttpClientConnectionManager cManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(cManager)
.build();
Then I tried a HttpGet request to http://www.google.com and everything worked fine.
Then I created a truststore via cmd and imported the certificate of the targeted website, setup a SSLConnectionSocketFactory with my truststore and set the SSLSocketFactory of httpClient:
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream inputStream = new FileInputStream(new File("myTrustStore.truststore"));
trustStore.load(inputStream, "nopassword".toCharArray());
inputStream.close();
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
PoolingHttpClientConnectionManager cManager = new PoolingHttpClientConnectionManager();
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(sslsf)
.setConnectionManager(cManager)
.build();
If I try to execute a Https HttpGet then I get a PKIX path building failed exception.
If I do the same without .setConnectionManager(cManager) everything works fine.
Can anyone of you tell me how I can get this to work? (Don't worry, I don't create any ddos tool)
Thanks in advance!
P.S.: I'm using HttpComponents 4.3.1
Found the answer:
https://stackoverflow.com/a/19950935/1223253
Just had to add
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory> create().register("https", sslsf).build();
and pass socketFactoryRegistry as parameter to the constructor of PoolingHttpClientConnectionManager.
Now it works just fine :)

Apache HttpClient resolving domain to IP address and not matching certificate

When using the Apache HttpComponents HttpClient library (4.0.2) I'm having a problem where the certificate doesn't get validated properly. The certificate is valid for the domain name (let's call it example.com) however it's getting validated against the IP address instead:
hostname in certificate didn't match: <123.123.123.123> !=
<*.example.com>
My code for making the connection is:
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
String url = "https://www.example.com";
HttpGet get = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(get);
String response = EntityUtils.toString(httpResponse.getEntity()).trim();
The certificate itself shows as valid when connecting through a web browser and is valid for the domain name I'm connecting to:
CN = *.example.com
The certificate is also added to the Java keystore (tested using regular HttpsURLConnection).
Any ideas why this code uses the IP address instead of the domain name?
Appears to be a known bug with HttpClient 4.0.2 - https://issues.apache.org/jira/browse/HTTPCLIENT-996
The bug suggests any of the following:
Upgrade to version 4.0.3 or newer
Downgrade to 4.0.1
Use the AllowAllHostnameVerifier

java HttpClient 403 forbidden problem?

I using HttpClient api to authenticate to a web site:
DefaultHttpClient httpclient = new DefaultHttpClient();
httpclient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, 443),
new UsernamePasswordCredentials(args[0], args[1]));
HttpGet httpget = new HttpGet("http://..........");
HttpResponse response = httpclient.execute(httpget);
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: "
+ entity.getContentLength());
}
I have this answer:
HTTP/1.1 403 Forbidden
Response content length: -1
But with a browser i have access to this page with the same login and password !!!!
How can i fix this problem ?
You construct the AuthScope object with the port parameter set to 443 (default port for HTTPS). However, you create the HttpGet object with the URL pointing to HTTP (with default port 80).
Either try to construct the AuthScope using:
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT)
or make sure that ports will match.
You need to look carefully at how the browser is actually authenticating.
What you are trying to do is (I think) send the credentials using HTTP Basic Authentication. If the site is set up to only allow form-based authentication and a session cookie, then it will ignore the header containing the credentials.
Check if the Version of the HttpClient you are using is whats causing the 403.
Try
HttpClient httpClient = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_1_1)
.build();

Categories