calling a http get request in java - 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>

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.

Error when sending email in Java

I have a problem with sending emails in Java. I am using the JavaMail api to send emails. I have a program which downloads an email attachment using pop3, reads the content, does some manipulation and then sends the result in an email using smtp.
The program works fine until the last step where it sends the email and I get the following exception.
javax.mail.MessagingException: Could not connect to SMTP host: localhost, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1961)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:654)
at javax.mail.Service.connect(Service.java:295)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.adidas.monitoring.SendMail.sendMail(SendMail.java:46)
at com.adidas.monitoring.MainClass.main(MainClass.java:115)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:321)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:237)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1927)
I am using the following code to send the email
public void sendMail(String strMailContent)
{
MimeMessage emailMessage;
Properties emailProperties = new Properties();
try {
emailProperties.load(new FileInputStream("Email.ini"));
} catch (IOException e){
DataLogger.logger.error(e.getMessage());
}
/*Get the properties from the email configuration file*/
String From = emailProperties.getProperty("Email.From");
String ToAdd = emailProperties.getProperty("Email.To");
String CC = emailProperties.getProperty("Email.CC");
String Subject = emailProperties.getProperty("Email.Subject");
String Host = emailProperties.getProperty("Email.Gateway");
emailProperties.setProperty("mail.smtp.host", Host);
Session emailSendSession = Session.getDefaultInstance(emailProperties);
try{
emailMessage = new MimeMessage(emailSendSession);
emailMessage.setFrom(new InternetAddress(From));
emailMessage.addRecipients(javax.mail.Message.RecipientType.TO,ToAdd);
emailMessage.addRecipients(javax.mail.Message.RecipientType.CC,CC);
emailMessage.setSubject(Subject);
emailMessage.setText(strMailContent);
Transport.send(emailMessage);
}
catch (Exception mailEx)
{
mailEx.printStackTrace();
}
}
The above code works fine when I use it with other programs. But when I am using it along with the pop3 code in this case, I have this error. Strange thing is the host is shown as localhost even though I set the property "mail.smtp.host".
Any help on this topic is really appreciated.

java net URL connection timeout

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.

Python Server / Java Client "Connection refused: connect"

I am communicating using TCP Socket.
While Working, a problem arises
Client can't make 'Socket' Instance.
Strange Point is that (In Server using Python)
Using 'socket' class in python don't cause problem,
but using 'SocketServer.TCPServer' class in python cause problem
This is my environment.
Server : Python
Client : Java / Many Users will try connect.
Server Code (using Python):
SooMain.py
if name == "main":
server = SooServer('localhost', PORT_DEBUG, SooRequestHandler)
server.serve_forever()
SooServer.py
class SooServer(SocketServer.TCPServer):
"This is Server For Project201201"
def __init__(self,
host='localhost',
port=PORT_DEBUG,
handler=SooRequestHandler):
#SocketServer.ThreadingTCPServer.__init__(self, (host, port), handler)
SocketServer.TCPServer.__init__(self, (host, port), handler)
print "SooServer <State> __init__"
self.abort=0
self.timeout=10
def shutdown(self):
SocketServer.ThreadingTCPServer.shutdown(self)
print "SooServer <State> shutdown"
Client Code (using Java):
TestJava.java
public class TestJava {
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
try {
String[] aStrData = {
"Test",
"Test" };
InetAddress m_oInetAddr = InetAddress.getByName(DEBUG_ADDR);
Socket m_oSocket = new Socket(m_oInetAddr, DEBUG_PORT); //This Line Makes Exception!!!!!
PrintWriter out =
new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(m_oSocket.getOutputStream())), true);
int nNumData = aStrData.length;
out.println(Integer.toString(nNumData));
for (int i=0 ; i<nNumData ; i++) {
out.println(aStrData[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Error Code (using Java):
Releated Line : Socket m_oSocket = new Socket(m_oInetAddr, DEBUG_PORT);
java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182)
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 java.net.Socket.<init>(Socket.java:425)
at java.net.Socket.<init>(Socket.java:241)
at TestJava.main(TestJava.java:51)

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