I have tried to connect to an https url using sample Java code I found on the web:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.cert.Certificate;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLPeerUnverifiedException;
public class SSLClientTest {
public static void main(String[] args) {
try {
URL hp = new URL("https://godaddy.com");
//URL hp = new URL("https://127.0.0.1:8443");
//URL hp = new URL("https://www.google.com/");
HttpsURLConnection hpCon = (HttpsURLConnection) hp.openConnection();
System.out.println("after connection made:");
int responseCode = hpCon.getResponseCode();
System.out.println("responseCode:" + responseCode);
boolean isProxy = hpCon.usingProxy();
System.out.println("is using proxy:" + isProxy);
InputStream obj = hpCon.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(obj));
String s;
while ((s = br.readLine()) != null) {
System.out.println("content >>" + s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
but get various error messages that I cannot resolve or resolve with any of the many internet posts on these error messages. How can I connect to an https url, ssl, with Java?
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1902)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
...
Caused by: java.security.cert.CertificateException: No subject alternative names present
at sun.security.util.HostnameChecker.matchIP(HostnameChecker.java:142)
at sun.security.util.HostnameChecker.match(HostnameChecker.java:91)
at sun.security.ssl.X509TrustManagerImpl.checkIdentity(X509TrustManagerImpl.java:347)
at
... 13 more
and
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:946)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
...
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:352)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
... 10 more
...
Caused by: javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:946)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1328)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1355)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:515)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1299)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at SSLClientTest.print_https_cert(SSLClientTest.java:56)
at SSLClientTest.main(SSLClientTest.java:21)
Caused by: java.io.EOFException: SSL peer shut down incorrectly
at sun.security.ssl.InputRecord.read(InputRecord.java:352)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)
... 10 more
Related
I am running an EC2 Instance RabbitMQ Ubuntu. I have started running the Rabbit MQ on it and it is listening on the public IPv4. I have provided a custom port number 15672, so it is hearing at http://***AWS PUBLIC IP****:15672. Everything is going but, when I am writing java code for both sender and receiver having error at host, which the aws public address and the rabbit mq port as well
Sender error:
Exception in thread "main" java.net.UnknownHostException: http://52.90.84.218:15672
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 com.rabbitmq.client.DnsRecordIpAddressResolver.resolveIpAddresses(DnsRecordIpAddressResolver.java:83)
at com.rabbitmq.client.DnsRecordIpAddressResolver.getAddresses(DnsRecordIpAddressResolver.java:73)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:56)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:900)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:859)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:817)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:954)
at com.demo.Send.main(Send.java:19)
Reciever error:
Exception in thread "main" java.net.UnknownHostException: http://52.90.84.218:15672
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 com.rabbitmq.client.DnsRecordIpAddressResolver.resolveIpAddresses(DnsRecordIpAddressResolver.java:83)
at com.rabbitmq.client.DnsRecordIpAddressResolver.getAddresses(DnsRecordIpAddressResolver.java:73)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:56)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:900)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:859)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:817)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:954)
at com.demo.Recv.main(Recv.java:24)
WHEN I AM using localhost as factory.sethost("localhost");
error as:
[AMQP Connection 127.0.0.1:5672] ERROR com.rabbitmq.client.impl.ForgivingExceptionHandler - An unexpected connection driver error occured
com.rabbitmq.client.MalformedFrameException: AMQP protocol version mismatch; we are version 0-9-1, server sent signature 3,1,0,0
at com.rabbitmq.client.impl.Frame.protocolVersionMismatch(Frame.java:170)
at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:107)
at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:164)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:571)
at java.lang.Thread.run(Unknown Source)
[AMQP Connection 0:0:0:0:0:0:0:1:5672] ERROR com.rabbitmq.client.impl.ForgivingExceptionHandler - An unexpected connection driver error occured
com.rabbitmq.client.MalformedFrameException: AMQP protocol version mismatch; we are version 0-9-1, server sent signature 3,1,0,0
at com.rabbitmq.client.impl.Frame.protocolVersionMismatch(Frame.java:170)
at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:107)
at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:164)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:571)
at java.lang.Thread.run(Unknown Source)
Exception in thread "main" java.io.IOException
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:105)
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:101)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:353)
at com.rabbitmq.client.impl.recovery.RecoveryAwareAMQConnectionFactory.newConnection(RecoveryAwareAMQConnectionFactory.java:62)
at com.rabbitmq.client.impl.recovery.AutorecoveringConnection.init(AutorecoveringConnection.java:99)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:900)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:859)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:817)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:954)
at com.demo.Recv.main(Recv.java:24)
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:66)
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:36)
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:372)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:297)
... 7 more
Caused by: com.rabbitmq.client.MalformedFrameException: AMQP protocol version mismatch; we are version 0-9-1, server sent signature 3,1,0,0
at com.rabbitmq.client.impl.Frame.protocolVersionMismatch(Frame.java:170)
at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:107)
at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:164)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:571)
at java.lang.Thread.run(Unknown Source)
Let me know where If at all I am going wrong
java code for both sender and receiver:
package com.demo;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
public class Recv {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException, TimeoutException {
// TODO Auto-generated method stub
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
Consumer consumer = new DefaultConsumer(channel) {
#Override
public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
byte[] body) throws IOException {
String message = new String(body, "UTF-8");
System.out.println(" [x] Received '" + message + "'");
}
};
channel.basicConsume(QUEUE_NAME, true, consumer);
}
}
Sender code:
package com.demo;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import java.io.IOException;
import java.util.concurrent.TimeoutException;
import com.rabbitmq.client.Channel;
public class Send {
private final static String QUEUE_NAME = "hello";
public static void main(String[] args) throws IOException, TimeoutException {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("http://52.90.84.218:15672");
Connection con = factory.newConnection();
Channel channel = con.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello Santosh";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
System.out.println(" [x] Sent '" + message + "'");
channel.close();
con.close();
}
}
UnknownHostException: http://52.90.84.218:15672
implies that you passed a URL to a method that expects a bare hostname or IP address. I.e. the API was expecting just 52.90.84.218 and not a full URL.
Thus where you have
factory.setHost("http://52.90.84.218:15672");
change it to
factory.setHost("52.90.84.218");
factory.setPort(15672);
I am learning about Sockets in Java and I am only missing how to receive back response from the server.
Following How to send string array object and How to send and receive serialized object in socket channel, I am trying to ask the user to pick as much as he wants out of choices:
1 - 2 - 3 - 4
And then I want to split and send them as an array to a server, where the server should send back the number of choices the user has picked.
For example if the user chose
2 3 4 1 2 3 4 1
Server should return
8
server is sending response fine, but on the client side I get error:
Exception in thread "main" java.net.ConnectException: Connection
refused: connect at java.net.DualStackPlainSocketImpl.connect0(Native
Method) at java.net.DualStackPlainSocketImpl.socketConnect(Unknown
Source) at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(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
java.net.Socket.(Unknown Source) at
java.net.Socket.(Unknown Source) at
ClientClass.main(ClientClass.java:26)
I am not sure why the issue. Any help?
My Client:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class ClientClass {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
// take order and convert it to array of choices
Scanner myScanner = new Scanner(System.in); // take from user
System.out.println("Enter all your choices seperated by space:");
System.out.println("Choices are: 1- 2- 3- 4");
String orderString = myScanner.next();
orderString += myScanner.nextLine();
String orderArray[] = orderString.split(" ");
// send request to server
Socket mySocket = new Socket("127.0.0.1", 4444); // create a socket
ObjectOutputStream out = new ObjectOutputStream(mySocket.getOutputStream());
out.writeObject(orderArray);
// get response from server
InputStream is = mySocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String message = br.readLine();
System.out.println("Message received from the server : " +message);
}
}
My Server:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
public class ServerClass {
public static void main(String args[]) throws IOException, ClassNotFoundException
{
// receive
ServerSocket myServerSocket = new ServerSocket(4444); // create a server socket
Socket mySimpleSocket = myServerSocket.accept(); // accept requests
ObjectInputStream ois = new ObjectInputStream(mySimpleSocket.getInputStream());
String[] choices = (String[]) ois.readObject();
// send back response
OutputStream os = mySimpleSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
bw.write(choices.length);
System.out.println("Message sent to the client is "+choices.length);
bw.flush();
}
}
server is sending response fine
Rubbish. The server isn't even getting an incoming connection, let alone reading the request, let alone sending a response.
but on the client side I get error:
Exception in thread "main" java.net.ConnectException: Connection refused: connect at
On this evidence the server wasn't even running. Certainly not running in the same host as the client, which is what is required by new Socket("127.0.0.1", 4444).
I know this is a very basic question, but some how I have managed to not find a solution to this problem. I have a java class that has a main method. In that method, I try to access an https url as below:
package helloworld;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class ConnectHttps
{
public static void main(String[] argsd)
{
System.out.println("***************Https testing started **************");
try
{
URL u = new URL("https://localhost:8443/myapp/test");
HttpsURLConnection http = (HttpsURLConnection) u.openConnection();
http.setAllowUserInteraction(true);
http.setRequestMethod("GET");
http.connect();
InputStream is = http.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line
+ "\n");
}
System.out.println(stringBuilder.toString());
System.out.println("***************Https testing completed **************");
}
catch (IOException e)
{
System.out.println("***************Https testing failed **************");
e.printStackTrace();
}
}
}
On executing this program, the output I get is:
***************Https testing started **************
***************Https testing failed **************
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No name matching localhost found
at sun.security.ssl.Alerts.getSSLException(Alerts.java:192)
at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1886)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:276)
at sun.security.ssl.Handshaker.fatalSE(Handshaker.java:270)
at sun.security.ssl.ClientHandshaker.serverCertificate(ClientHandshaker.java:1341)
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:153)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:868)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:804)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1016)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:515)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:153)
at helloworld.ConnectHttps.main(ConnectHttps.java:59)
I guess I am doing a very basic mistake here.
I am using JDK 1.7.0_25.
java.net.ConnectException: Connection timed out: connect
This is not really related to SSL/TLS. Rather, your client can't connect to the server at all (at least not within a reasonable time).
It's quite possible that there's a firewall preventing you from making such connections.
You might have to go through a proxy, in which case setting the https.proxyHost and https.proxyPort system properties should be taken into account by HttpsURLConnection.
I have the following code:
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.cert.X509Certificate;
public class TrackWrapper {
public static void main(String[] args) throws Exception {
/*
* fix for
* Exception in thread "main" javax.net.ssl.SSLHandshakeException:
* sun.security.validator.ValidatorException:
* PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
* unable to find valid certification path to requested target
*/
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) { }
public void checkServerTrusted(X509Certificate[] certs, String authType) { }
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create all-trusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the all-trusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
/*
* end of the fix
*/
URL url = new URL("https://somedomain.com:1234");
URLConnection con = url.openConnection();
con.connect();
}
}
The first part of that is simply a copypasted quickfix to accept every certificate I've got from another StackOverflow Question (I'm sure that this isn't exactly ready for production), on the second part I try to connect to some SSL-secured site whichs client certificate is in my keystore, I receive the following error message:
Exception in thread "main" javax.net.ssl.SSLHandshakeException: Received fatal alert: bad_certificate
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:136)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.recvAlert(SSLSocketImpl.java:1806)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:986)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1170)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1197)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1181)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:133)
at TrackWrapper.main(TrackWrapper.java:54)
As I admittedly am rather clueless about SSL I'd be grateful for some insight and a walkthrough on how to fix this problem.
After some tries I now get the following error:
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(SocketInputStream.java:129)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:830)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.waitForClose(SSLSocketImpl.java:1555)
at com.sun.net.ssl.internal.ssl.HandshakeOutStream.flush(HandshakeOutStream.java:103)
at com.sun.net.ssl.internal.ssl.Handshaker.sendChangeCipherSpec(Handshaker.java:689)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.sendChangeCipherAndFinish(ClientHandshaker.java:985)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.serverHelloDone(ClientHandshaker.java:904)
at com.sun.net.ssl.internal.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:238)
at com.sun.net.ssl.internal.ssl.Handshaker.processLoop(Handshaker.java:593)
at com.sun.net.ssl.internal.ssl.Handshaker.process_record(Handshaker.java:529)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:925)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1170)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1197)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1181)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:434)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:166)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:133)
at TrackWrapper.main(TrackWrapper.java:54)
You should have correct SSL certificate in your keystore, of server to whom you are trying to connect. Check these examples. These are working for me.
example 1
example 2
You can export that server certificate from browser (if accessible) or there are other ways to get certificates over the internet. Your certificates should match. Once you get certificate you can make keystore from any tool. alternatively you can make keystore from this code.
Have you checked if you need a client certificate?
The error message could also be from the server side.
Also start your client with the parameter -Djavax.net.debug=all. There you should see some more hints about what failed.
following is my code to send mail:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class SendMail {
public void sendMail(String m_from,String m_to,String m_subject,String m_body){
try {
Session m_Session;
Message m_simpleMessage;
InternetAddress m_fromAddress;
InternetAddress m_toAddress;
Properties m_properties;
m_properties = new Properties();
m_properties.put("mail.smtp.host", "usdc2spam2.slingmedia.com");
m_properties.put("mail.smtp.socketFactory.port", "465");
m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
m_properties.put("mail.smtp.auth", "true");
m_properties.put("mail.smtp.port", "9000");
m_Session=Session.getDefaultInstance(m_properties,new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("aaaaa","bbbbb#1"); // username and the password
}
});
m_simpleMessage = new MimeMessage(m_Session);
m_fromAddress = new InternetAddress(m_from);
m_toAddress = new InternetAddress(m_to);
m_simpleMessage.setFrom(m_fromAddress);
m_simpleMessage.setRecipient(RecipientType.TO, m_toAddress);
m_simpleMessage.setSubject(m_subject);
m_simpleMessage.setContent(m_body, "text/html");
//m_simpleMessage.setContent(m_body,"text/plain");
Transport.send(m_simpleMessage);
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
SendMail send_mail = new SendMail();
String empName = "xxxxx";
String title ="<b>Hi !"+empName+"</b>";
send_mail.sendMail("123erft#slingmedia.com", "abz#gmail.com", "Please apply for leave for the following dates", title+"<br>by<br><b>HR<b>");
}
}
but when i run the code it gives me the following exception.
javax.mail.MessagingException: Could not connect to SMTP host: usdc2spam2.slingmedia.com, port: 9000;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1934)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:638)
at javax.mail.Service.connect(Service.java:317)
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 samples.SendMail.sendMail(SendMail.java:46)
at samples.SendMail.main(SendMail.java:55)
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:288)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:231)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1900)
when i ping this usdc2spam2.slingmedia.com it gives me reply without any problem. I am using windows 7
Please help me to resolve this.
This is these two lines which was casting me the problem :
m_properties.put("mail.smtp.socketFactory.port", "465");
m_properties.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
and added this line :
m_properties.put("mail.smtp.starttls.enable", "true");
After removing and adding the above lines of code it worked fine.
What causes your problem is right there in the stack trace:
java.net.ConnectException: Connection refused: connect
do you need a password to connect to the SMTP server? Are you sure you are using the right settings (as in port number)? Are you behind a proxy or a firewall? Can you use those settings in a regular mail program (e.g. Thunderbird) and send mails?
This exception usually occurs when there is no service listening on the port you are trying to connect to.
Try to connect using putty or telnet. I can bet you will get the same error.
Verify these things:
Host name and port you're trying to connect to,
The server is listening correctly, and
There's no firewall blocking the connection.
Try to add port 9000 to your inbound rules in your windows firewall.