com.sun.jersey.api.client.ClientHandlerException Connection timed out: connect - java

I want to ask you a question about this exception. I need more information but i dont find anything. Actually this test i am receiving this exception:
com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection timed out: connect
The url also exists and retrieve me data if i put that url in a browser. The exception raises in the line of the ClientResponse. Please give more info. Actually im using a proxy to establish connection with the server , but my data are OK, in my project.properties. Any idea why happens this??. Im communicating with a remote server , no in localhost.
Client client = Client.create();
WebResource webResource = client
.resource("http://someurl");
String input= "{'test'}";
ClientResponse response = webResource.type("application/json")
.post(ClientResponse.class, input);

Related

ResourceAccessException when trying to execute a post service

I am getting this exception
org.springframework.web.client.ResourceAccessException
I/O error on POST request for \"http://host.docker.internal:8073/user-management/users/login\": Connection timed out: connect; nested exception is java.net.ConnectException: Connection timed out: connect",
My code looks like this
#Resource(name="restTemp")
private RestTemplate restTemplate;
String url = "user-management/users/login";
//String fullUrl = "https://localhost:8073/user-management/users/login";
InstanceInfo instance = eurekaClient.getNextServerFromEureka("user-management", false);
LoginRequest user = restTemplate.postForObject(instance.getHomePageUrl()+url, loginRequest, LoginRequest.class);
Also I dont understand why instance.getHomePageUrl() generates a internal docker url . what could be the reason behind this docker desktop is running.
I need help in resolving this exception.According to what I could find this exception occurs when we are trying to access a third party url
Just try increasing the context timeout for request sent by RestTemplate

JSoup Attempts to Connect to wrong URL

I'm trying to connect to a URL in an AsynTask but am having trouble.
Document doc = Jsoup.connect("https://www.gasbuddy.com/home?search=33444&fuel=1").get();
gives me an error in my log saying:
Error Connecting: failed to connect to www.gasbuddy.com/104.17.148.191 (port 443) after 30000ms
After doing some research, I believe I need to connect to the baseURL. However, I'm not sure how to do this. I've tried:
URL absoluteUrl = new URL(new URL("https://www.gasbuddy.com/home?search=33444&fuel=1"), "script.js");
Document doc = Jsoup.connect(String.valueOf(absoluteUrl)).get();
But I get the same error in my my logs.
Edit: I get the same error on any website I try connecting too ("https://www.yahoo.com/", "https://www.google.com/", etc) I'm on a a public Starbucks Wifi at the moment, not sure if that matters.

Java simple code: java.net.SocketException: Unexpected end of file from server

I wrote some simple code in Java, the method should connect to the website and return the BufferedReader.
private BufferedReader getConnection(String url_a) {
URL url;
try {
System.out.println("getting connection");
url = new URL(url_a);
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
urlConnection.addRequestProperty("User-Agent",
"Mozilla/5.0 (X11; U; Linux i586; en-US; rv:1.7.3) Gecko/20040924"
+ "Epiphany/1.4.4 (Ubuntu)");
inStream = new InputStreamReader(urlConnection.getInputStream());
return new BufferedReader(inStream);
} catch (Exception ex) {
Logger.getLogger(Reader.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
When I use it on my PC, it works fine but when I put .jar file on the server I get this error:
java.net.SocketException: Unexpected end of file from server
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:718)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:715)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1322)
at dataconverter.Reader.getConnection(Reader.java.260)
Problem is quite strange because the exception isn't thrown each time, sometimes everything is OK and program works fine.
Has anybody got any ideas?
"Unexpected end of file" implies that the remote server accepted and closed the connection without sending a response. It's possible that the remote system is too busy to handle the request, or that there's a network bug that randomly drops connections.
It's also possible there is a bug in the server: something in the request causes an internal error, and the server simply closes the connection instead of sending a HTTP error response like it should. Several people suggest this is caused by missing headers or invalid header values in the request.
With the information available it's impossible to say what's going wrong. If you have access to the servers in question you can use packet sniffing tools to find what exactly is sent and received, and look at logs to of the server process to see if there are any error messages.
Summary
This exception is encountered when you are expecting a response, but the socket has been abruptly closed.
Detailed Explanation
Java's HTTPClient, found here, throws a SocketException with message "Unexpected end of file from server" in a very specific circumstance.
After making a request, HTTPClient gets an InputStream tied to the socket associated with the request. It then polls that InputStream repeatedly until it either:
Finds the string "HTTP/1."
The end of the InputStream is reached before 8 characters are read
Finds a string other than "HTTP/1."
In case of number 2, HTTPClient will throw this SocketException if any of the following are true:
The HTTP method is CONNECT
The HTTP method is POST and the client is set to streaming mode
Why would this happen
This indicates that the TCP socket has been closed before the server was able to send a response. This could happen for any number of reasons, but some possibilities are:
Network connection was lost
The server decided to close the connection
Something in between the client and the server (nginx, router, etc) terminated the request
Note: When Nginx reloads its config, it forcefully closes any in-flight HTTP Keep-Alive connections (even POSTs), causing this exact error.
I do get this error when I do not set the Authentication header or I set wrong credentials.
I would suggest using wire shark to trace packets. If you are using Ubuntu, sudo-apt get wireshark. Like Joni stated the only way to figure out whats going wrong is to follow the GET requests and their associated responses.
http://www.wireshark.org/download.html
In my case it was solved just passing proxy to connection. Thanks to #Andreas Panagiotidis.
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("<YOUR.HOST>", 80)));
HttpsURLConnection con = (HttpsURLConnection) url.openConnection(proxy);
In my case url contained wrong chars like spaces . Overall log your url and in some cases use browser.
Most likely the headers you are setting is incorrect or not acceptable.
Example:
connnection.setRequestProperty("content-type", "application/json");
I got this exception too. MY error code is below
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
connection.setRequestProperty("Content-type", "JSON");
I found "Content-type" should not be "JSON",is wrong!
I solved this exception by update this line to below
connection.setRequestProperty("Content-type", "application/json");
you can check up your "Content-type"

What causes HttpHostConnectException?

I have a Auto Complete/type ahead feature on Search for my website. I see that some time their is an exception associated with it. We are using a proxy server.
org.apache.http.conn.HttpHostConnectException: Connection to http://proxy.xyz.com:60 refused
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:159)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:108)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
at com.xxx.dd.sone.integration.SearchDAO.getJSONData(SearchDAO.java:60)
at com.xxx.dd.sone.integration.SearchDAO.searchAutoCompleteResults(SearchDAO.java:560)
at com.xxx.dd.sone.presentation.util.SearchAutoCompleteUtil.doGet(SearchAutoCompleteUtil.java:26)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:845)
at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:242)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:352)
at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:236)
at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3254)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:57)
at weblogic.servlet.internal.WebAppServletContext.doSecuredExecute(WebAppServletContext.java:2163)
at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2074)
at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1512)
at weblogic.servlet.provider.ContainerSupportProviderImpl$WlsRequestExecutor.run(ContainerSupportProviderImpl.java:255)
at weblogic.work.ExecuteRequestAdapter.execute(ExecuteRequestAdapter.java:22)
at weblogic.kernel.ExecuteThread.execute(ExecuteThread.java:147)
at weblogic.kernel.ExecuteThread.run(ExecuteThread.java:119)
Caused by: java.net.ConnectException: Connection refused
Here is the how i have coded
public HashMap<String, Object> getJSONData(String url)throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
try {
HttpConnectionParams.setConnectionTimeout(params, 10000);
HttpConnectionParams.setSoTimeout(params, 10000);
} catch (Exception e) {
e.printStackTrace();
throw e;
}
HttpHost proxy = new HttpHost(proxy.xyz.com, 60);
ConnRouteParams.setDefaultProxy(params, proxy);
URI uri;
InputStream data = null;
uri = new URI(url);
HttpGet method = new HttpGet(uri);
HttpResponse response=null;
try {
response = httpClient.execute(method);
}catch(Exception e) {
e.printStackTrace();
throw e;
}
data = response.getEntity().getContent();
Reader r = new InputStreamReader(data);
HashMap<String, Object> jsonObj = (HashMap<String, Object>) GenericJSONUtil.fromJson(r);
return jsonObj;
}
Can any one tell me why i am getting this exception some time only? is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications
A "connection refused" error happens when you attempt to open a TCP connection to an IP address / port where there is nothing currently listening for connections. If nothing is listening, the OS on the server side "refuses" the connection.
If this is happening intermittently, then the most likely explanations are (IMO):
the server you are talking ("proxy.xyz.com" / port 60) to is going up and down, OR
there is something1 between your client and the proxy that is intermittently sending requests to a non-functioning host, or something.
Is this possible that this exception is caused when a search request is made from Android applications as our website don't support a request is being made from android applications.
It seems unlikely. You said that the "connection refused" exception message says that it is the proxy that is refusing the connection, not your server. Besides if a server was going to not handle certain kinds of request, it still has to accept the TCP connection to find out what the request is ... before it can reject it.
1 - For example, it could be a DNS that round-robin resolves the DNS name to different IP addresses. Or it could be an IP-based load balancer.
In my case the issue was a missing 's' in the HTTP URL. Error was:
"HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.
You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document

HttpURLConnection returns 503 error when accessed through proxy

I am working on creating a Video sitemap for a site that has hosted videos on Brightcove video cloud. In order to get all the video information from the site, Brightcove suggests to read the response from their url of following form
http://api.brightcove.com/services/library?token="+accountToken+"&page_size=1&command=find_all_videos&output=JSON&get_item_count=true
the output of the url is in JSON, where accountToken is just an identifier of the account.
When I hit the above url with Token in the browser, it gives me the correct response.
I wrote below program snippet to read from that url
URL jsonURL = new URL("http://api.brightcove.com/services/library?token="+accountToken+"&page_size=1&command=find_all_videos&output=JSON&get_item_count=true");
HttpURLConnection connection = (HttpURLConnection) jsonURL.openConnection();
connection.setRequestMethod("GET");
connection.connect();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
String lineRead = "";
while (reader.ready()) {
lineRead = lineRead + reader.readLine();
}
As my browser uses proxy, I added below code to include proxy settings
System.setProperty("http.proxyHost", "my.proxyurl.com");
System.setProperty("http.proxyPort", "80");
Without using proxy settings, it returns java.net.ConnectException: Connection refused: connect and with proxy it gives me java.io.IOException: Server returned HTTP response code: 503
So my question is , why is it giving me a 503(Service Unavailable) error ? From the browser its working fine.
Update 1:
It seems like an issue with the Network. I pinged the domain and it said "Request Timed out". Working via HTTP though. Looks like an issue with the Firewall.
I think, it may due to your internet connection, I have tried your code I didn't get any 503(Service Unavailable). Check out with different connection connection(without proxy) and it should work. Or you can try it with slightly different approach:
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("host", "port));
conn = new URL(jsonURL).openConnection(proxy);
If you have SOCKS type proxy, change Proxy's constructor parameter to Proxy.Type.SOCKS.
Minor correction to Jamas code
String host="myproxy.com";
int port=8080;
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port));

Categories