java net URL connection timeout - java

I am trying to fetch and download file in html format. Following is the code block:
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setProperty("http.proxyPort", "8080");
URL url = new URL("http://www.java2s.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
Here, when i am trying to Run this java file it show me following error:
D:\Build>javac URLReader.java
D:\Build>java URLReader
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:529)
at java.net.Socket.connect(Socket.java:478)
at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:523)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:227)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:977)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:925)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:836)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
at java.net.URL.openStream(URL.java:1010)
at URLReader.main(URLReader.java:12)
I don't think there any problem with code because When i tried to run this code at Home it worked for me. But when i tried it in my office it showed me the error!
So i guess there must be some kind of blockage in my office.
Can i set any proxy here in code so that it might work?

If you are behind a proxy you need to configure Java to use it. Read here on how to set your proxy for your network program

Try this as mentioned in this link http://docs.oracle.com/javase/6/docs/technotes/guides/net/proxies.html
//Set the http proxy to webcache.mydomain.com:8080
System.setProperty("http.proxyHost", "webcache.mydomain.com");
System.setPropery("http.proxyPort", "8080");
// Next connection will be through proxy.
URL url = new URL("http://java.sun.com/");
InputStream in = url.openStream();
// Now, let's 'unset' the proxy.
System.setProperty("http.proxyHost", null);
// From now on http connections will be done directly.

Related

Forwarding Java HTTP Requests through another server

I have two AWS Instance I1 and I2 having Ip addresses as ip1 and ip2 respectively.What I want to achieve is:
I want to hit a url from I1(using java httpclient) and want that request should go through I2 instance i.e to outside world it should appear that the request is coming from instance I2.
For Example :
I am executing the below-mentioned code from instance I1 :
class Test {
public static void main(String[] args) {
String url = "https://api.ipify.org?format=json",
proxy = "ip2";
Proxy p = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy, 80));
URL server = new URL(url);
Properties systemProperties = System.getProperties();
HttpURLConnection connection = (HttpURLConnection)server.openConnection(p);
connection.connect();
String theString = IOUtils.toString(connection.getInputStream(), StandardCharsets.UTF_8);
System.out.println(theString);
}
}
The Output should be public Ip of instance I2. But it is throwing the exception:
Exception in thread "main" java.net.ConnectException: Connection refused (Connection refused)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient$1.run(HttpClient.java:515)
at sun.net.www.http.HttpClient$1.run(HttpClient.java:513)
at java.security.AccessController.doPrivileged(Native Method)
at sun.net.www.http.HttpClient.privilegedOpenServer(HttpClient.java:512)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:553)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1199)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:162)
at sun.net.www.protocol.https.HttpsURLConnectionImpl$connect.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:117)
at com.exp.Test.main(Test.java:24)
I have googled for the above mentioned use case but was not able to find anything. Any help is appriciated.
This issue is fixed.
Installed squid server on instance I2.

java.net.UnknownHostException when attempting to connect to database

I am attempting to connect to an Oracle database through Java with the Oracle JDBC driver with the following code (obscuring the host, service, user, and password):
import java.sql.*;
public class Main {
public Main () {
try {
String host = "HOST_NAME";
String port = "1521";
String service = "SERVICE_NAME";
String user = "SCHEMA_USER";
String password = "SCHEMA_PASSWORD";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection("jdbc:oracle:thin:#(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=" +
host +
")(PORT=" +
port +
")))(CONNECT_DATA=(SERVICE_NAME=" +
service +
")))",
user,
password);
connection.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main (String args) {
new Main ();
}
}
However, I receive the following error:
java.sql.SQLException: IO Error: The Network Adapter could not establish the connection
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:458)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:546)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:236)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:32)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:521)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.acxiom.axle.reporting.database.DatabaseConnection.connect(DatabaseConnection.java:23)
at com.acxiom.axle.reporting.Reporting.establishDatabaseConnection(Reporting.java:53)
at com.acxiom.axle.reporting.Reporting.beginReporting(Reporting.java:20)
at com.acxiom.axle.reporting.Entry.<init>(Entry.java:28)
at com.acxiom.axle.reporting.Entry.main(Entry.java:118)
Caused by: oracle.net.ns.NetException: The Network Adapter could not establish the connection
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:392)
at oracle.net.resolver.AddrResolution.resolveAndExecute(AddrResolution.java:434)
at oracle.net.ns.NSProtocol.establishConnection(NSProtocol.java:687)
at oracle.net.ns.NSProtocol.connect(NSProtocol.java:247)
at oracle.jdbc.driver.T4CConnection.connect(T4CConnection.java:1102)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:320)
... 11 more
Caused by: java.net.UnknownHostException: null
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(Unknown Source)
at java.net.InetAddress.getAddressesFromNameService(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at oracle.net.nt.TcpNTAdapter.connect(TcpNTAdapter.java:117)
at oracle.net.nt.ConnOption.connect(ConnOption.java:133)
at oracle.net.nt.ConnStrategy.execute(ConnStrategy.java:370)
... 16 more
The strange thing is, I can connect to the database from PL/SQL Developer, I can ping the remote host, and I can telnet to the remote host on port 1521.
Why would only Java appear to give an UnknownHostException, but I can connect and ping the host with other applications?
EDIT: I removed "hr/hr" from the connection string above. I have tried the connection as-is with it removed and still receive the same error. I've also tried changing the connection string to match the version morgano listed in his answer, with the same result. Finally, I tried to change the port number to a port I know it's not listening on, and it still receives the same error.
The connection string is of the correct format. The problem is that the host isn't set. It's null, or perhaps the string "null". There's simply no other way to generate the error message java.net.UnknownHostException: null
In your sample code, you write String host = "HOST_NAME";. This makes it look like in your real code you are assigning a constant string to the variable host. However, I'm going to stick my neck out and say that in your real code you are not doing this. You are looking up the host name from somewhere, this lookup fails for some reason, you don't check this, and hence you pass a null value into the connection string.
Your JDBC url is wrong, according to the documentation it should be something like:
jdbc:oracle:driver_type:[username/password]#//host_name:port_number/service_name
In your case your code would be something like:
import java.sql.*;
public class Main {
public Main () {
try {
String host = "HOST_NAME";
String port = "1521";
String service = "SERVICE_NAME";
String user = "SCHEMA_USER";
String password = "SCHEMA_PASSWORD";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection = DriverManager.getConnection(
"jdbc:oracle:thin:#//" + host
+ ":" + port + "/" + service, user, password);
connection.close ();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main (String args) {
new Main ();
}
}

Trying connect to DriveHq ftp client and upload the file

My code is for connecting to drivehq ftp client is
FTPClient client = new FTPClient();
public boolean upload(File file){
client.enterLocalPassiveMode();
client.connect("ftp.drivehq.com");
client.login("username", "password");
client.enterLocalPassiveMode();
fis = new FileInputStream(file);
status= client.storeFile(" /c/"+file.getName(), fis);
client.logout();
fis.close();
}
and the error message i'm getting is
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:194)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:273)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read(BufferedInputStream.java:254)
at org.apache.commons.net.telnet.TelnetInputStream.__read(TelnetInputStream.java:114)
at org.apache.commons.net.telnet.TelnetInputStream.run(TelnetInputStream.java:535)
at java.lang.Thread.run(Thread.java:722)
I have seen this code is working in one video in sep-2014 but now it's not working?
I am not familiar with the FTPClient class, but it seems the following line is incorrect:
client.storeFile(" /c/"+file.getName(), fis)
Please test a simple path with the file name only first.

calling a http get request in java

I want the request of http get request using the following java code.
But, uncertainly i am getting the following exception.
import java.net.*;
import java.io.*;
public class API {
public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
The Error or exception is as follows:
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:69)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:337)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:198)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:180)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:157)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:391)
at java.net.Socket.connect(Socket.java:579)
at java.net.Socket.connect(Socket.java:528)
at sun.net.NetworkClient.doConnect(NetworkClient.java:180)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:388)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:483)
at sun.net.www.http.HttpClient.<init>(HttpClient.java:213)
at sun.net.www.http.HttpClient.New(HttpClient.java:300)
at sun.net.www.http.HttpClient.New(HttpClient.java:316)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:992)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:928)
at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:846)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1296)
at API.main(API.java:8)
I'm guessing you have a firewall and it's blocking this HTTP get request.
You code should work as you expect it. Something outside the Java runtime is preventing the connection.
Check whether you can ping to http://www.oracle.com/.
If you can ping check whether you are behind a proxy server.
If so provide -Dhttp.proxyHost and -Dhttp.proxyPort while starting the JVM
java -Dhttp.proxyHost=<Your Proxy Server Name/IP> -Dhttp.proxyPort=<Your Proxy Server Port>

Socket Programming in java

I was executing a socket program.The program is to, just echo the user input ,
by the server .ie if the user gives input as Apple the server reply should be Apple.
But the problem now i am facing is, the server is sending a message(instead of Apple ) which used to be the Banner Message that we get when we login to the server.Once the banner message is over ,the following error gets displayed :
Exception in thread "main" java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at EchoClient.main(EchoClient.java:69)
Following is my code :
import java.net.*;
import java.io.*;
public class EchoClient
{
public static void main(String[] args) throws IOException
{
Socket echosocket = null;
PrintWriter out =null;
BufferedReader in=null;
//establish the socket connection between the client and the server
// open a PrintWriter and a BufferedReader on the socket:
try
{
echosocket = new Socket("ltesol1.comm.mot.com",22);
out=new PrintWriter(echosocket.getOutputStream(),true);
in=new BufferedReader(new InputStreamReader(echosocket.getInputStream()));
}
catch(UnknownHostException e)
{
System.err.print("Unable to find the host dkc678-01");
System.exit(1);
}
catch(IOException e)
{
System.err.print("No IO for host dkc678-01");
System.exit(1);
}
BufferedReader stdIn=new BufferedReader(new InputStreamReader(System.in));
String userInput;
while((userInput =stdIn.readLine())!= null )
{
out.println(userInput);
System.out.println("echo :" + in.readLine());
}
out.close();
in.close();
stdIn.close();
echosocket.close();
}
}
If you want too connect to a SSH-Server, you have to use the ssh-protocol: http://javassh.org
You should find the sources of a ssh-client there.
Can you please comment on my suggestion that another service (ie sshd/telnet server) is listening to port 22 on the server side? Or otherwise give us the server code?
Port 22 is usually used for ssh which is an encrypted connection. You can't use a plain text stream.
In either case, the server is disconnecting the connection. You need to find out why it is doing that.

Categories

Resources