`java.net.SocketException: Connection reset` on a request with proxy - java

I am trying to send a HTTP POST request to a site with a HTTPS proxy.
I am currently doing it like that:
System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
HttpPost request = new HttpPost("https://example.com");
HttpHost proxy2 = new HttpHost("proxy ip here", 8080, "https");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy2)
.build();
request.setConfig(config);
String json = "\"" + username + "\"";
StringEntity entity = new StringEntity(json);
request.setEntity(entity);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
CloseableHttpResponse response = httpclient.execute(request, context);
HttpEntity entityresponse = response.getEntity();
responseString = EntityUtils.toString(entityresponse, "UTF-8");
response.close();
httpclient.close();
But I am getting this: java.net.SocketException: Connection reset
I've tried a lot of proxies and different URLs too but the same problem is there.
It work fine if I set a HTTP URL and the http parameter in the proxy host line, but I want HTTPS :/
Any help would be appreciated.
Thanks!

If you want to call https url, you must have to install the certificate in your jre security/lib folder.
In order to install the certificate, please follow below steps:
Download InstallCert.java file from : https://confluence.atlassian.com/download/attachments/180292346/InstallCert.java?version=1&modificationDate=1315453596921
copy InstallCert.java to any location.
run: javac InstallCert.java
run: java InstallCert example.com:port
jssecacerts file will be generated
Copy it inside JAVA_HOME\jre\lib\security folder
I hope this should resolve your issue.

Related

Docker Image and Java HTTP Post Request

I have a task to ping and endpoint using a post request. The issue I am having is the full endpoint is not clearly defined. I have a docker image and container but I am not sure how to use it in order to make a successful api call.
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost("/auth");
//Auth object just has 1 field called account
Auth a = new Auth("Test-acc");
Gson gson= new Gson();
String json = gson.toJson(a);
System.out.println("Json: " + json);
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Api-Key", "API Key is given for Test-acc");
CloseableHttpResponse response = client.execute(httpPost); //error as unknown endpoint?
client.close();
//read response
HttpEntity res = response.getEntity();
String result = EntityUtils.toString(res);
The error I get is: client.ClientProtocolException. The endpoint /auth gives me back a session token but I am unsure how to call the full endpoint (e.g. https://.../auth). I assume it has something to do with the docker container that is provided.
To test that the container is running I run docker run and get the response {"message": "ok"}. But other than that, I am unsure how to use it. Will the image in the container help with this?
Docker run command:
docker run -p 7902:7902 tesingCompany/testprovider
You have two choices :
You lanch this code from another container on the same user defined docker network, in this case the host is the container name
You launch this code from your host and you need to link a port from your host to a port on your container. You do that when you launch your container with the -p 7092:7092 option. It means your host 7092 port is linked to your container 7092, and you can contact it with localhost:7092

Setting a cookie in Apache Components HttpClient but unable to retrieve at the server in HttpServletRequest

I'm adding a cookie to Closeable HttpClient object and attempt to retrieve the same at the Server as below.
BasicClientCookie mCookie = new BasicClientCookie("myCookie", "dummyValue");
mCookie.setDomain(".myCookie.net");
mCookie.setPath("/");
mCookie.setSecure(true);
mCookie.setAttribute(ClientCookie.PATH_ATTR, "/");
mCookie.setAttribute(ClientCookie.DOMAIN_ATTR, ".myCookie.net");
mfCookies[0] = mCookie;
BasicCookieStore basicCookieStore = new BasicCookieStore();
basicCookieStore.addCookies(mfCookies);
CloseableHttpClient httpClient = HttpClients.custom()
.setDefaultRequestConfig(
RequestConfig.custom().setConnectTimeout(connectionTimeOut).build())
.setDefaultCookieStore(basicCookieStore)
.setConnectionManager(poolingConnectionManager)
.build();
I connect to local url using HttpGet object as below
httpGet = new HttpGet(myLocalUrl);
httpResponse = httpClient.execute(httpGet);
HttpClient hits the local url correctly connecting to Rest end point on local host but when I try to retrieve cookies using code below
(HttpServletRequest) request.getCookies() ;//returns null
I get null.
Can someone please help - I'm using spring boot to make a Rest end point (server) and attempt to retrive the cookie.
I figured it out myself, actually I was setting the domain as .myCookie.net while I was connecting to http://localhost:8080/..., if running on local, the localhost should resolve to the domain name by dns so in this case .myCookie.net should be mapped to localhost in file /etc/hosts file.
eg set 127.0.0.1 www.myCookie.net in etc/hosts file and hit the url http://www.myCookie.net/...
If the url the httpclient connects to and the domain set in the cookie dont match, httpclient will just drop the cookies.

use a specific ip address for outgoing request in java

I try to do a http request from my server and want to use different ip addresses (do one request with one IP and another with another IP). I read that it should work with the http client of apache. This is the code i use:
HttpClientBuilder builder = HttpClients.custom();
Builder configBuilder = RequestConfig.custom();
configBuilder.setLocalAddress(InetAddress.getByAddress(new byte[] {85,2,(byte) 246,4}));
CloseableHttpClient httpClient = builder.setDefaultRequestConfig(configBuilder.build()).build();
HttpGet httpGet = new HttpGet("http://xy.com/");
CloseableHttpResponse response1 = httpClient.execute(httpGet);
//do something with the response
response1.close();
resulting in the following exception:
Exception in thread "main" java.net.BindException: Cannot assign requested address: JVM_Bind
at the line "CloseableHttpResponse response1 = httpClient.execute(httpGet);"
What am I doing wrong? (It don't has to be done with apache, it just needs to be java. Best would be Play Framework because I normally do my request with that but I just want it to work, anything else is secondary)
Thanks

How to emulate a browser HTTPS POST request with Java (Apache HTTP Client)?

There is a website with an AJAX API. I have opened Firebug to look into the details of the login HTTPS POST request.
Then I have tried to do the same POST request from my Java program using Apache HTTP Client. But somehow the server identified my request as a non browser request. It sends a security exception message, which tells me that.
When all request headers are the same, what else could identify my client as not a browser?
My guess is that it's a cookie issue (e.g. JSESSIONID the browser has stored). Include the session information with your POST. Have a look at the cookies of this site. Try disabling cookies for this site a have a look a the request again.
user-agent header? "httpclient.useragent" property
Use debug mode to see full wire logging and compare the request with firebug's one.
Dont know about the POST request but there is this for a multipart request
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
see if its of any help
EDIT: Code sample for a multipart request
String createOrderUrl = Constants.CREATE_ORDER_URL;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(createOrderUrl);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
// add the information to the multipart request
entity.addPart("msisdn", new StringBody("something"));
entity.addPart("recipientname", new StringBody("something"));
entity.addPart("recipientnumber", new StringBody("something"));
entity.addPart("recipientaddress", new StringBody("something"));
// add the images
for (String imagePath : selectedImages)
{
FileBody bin = new FileBody(new File(imagePath));
entity.addPart("image", bin);
}
httpPost.setEntity(entity);
return httpClient.execute(httpPost);

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