问题
I want to connect to a sms gateway. I found the following code.
public void smsSender(String username, String password, String to,
String text) throws IOException {
try {
String data = "username=" + username + "&password=" + password
+ "&to=" + to + "&text=" + text;
URL url = new URL("https://sendsms.abc.com:1010/sms.php");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setRequestMethod("POST");
urlc.setDoOutput(true);
urlc.setRequestProperty("Content-type",
"application/x-www-form-urlencoded");
BufferedWriter br = new BufferedWriter(new OutputStreamWriter(
urlc.getOutputStream()));
br.write(data);
br.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(
urlc.getInputStream()));
String line;
while (null != ((line = rd.readLine()))) {
output = line;
System.out.println(output);
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
}
}
When i try to connect using this method Eclipse sends an error message.
unable to find valid certification path to requested target
The server that i'm trying to access is using self signed certificate. I'm new to this field. How can i solve this problem. Thanks in advance :)
回答1:
To make remote method invocations over SSL, a client needs to trust the certificate of the server. As you said the server has a self-signed certificate, you client needs to be explicitly configured to trust the certificate else the connection fails. To create a trust relationship between a client and server's self-signed certificate, follow the steps mentioned below,
First you should get the server certificate on your client side.
For that the way I know of is, i.e. hit the server url in a browser and get the server's certificate and import it in the browser. There might be other ways of getting the server certificate but you'll have to explore.Now export the public key as a certificate from the browser to the client. let it be server.cer.
Now, create the client keystore
keytool -genkey -alias clientkeys -keyalg RSA -keystore client.keystore -storepass 123456 -keypass 123456 -dname "CN=localhost, OU=MYOU, O=MYORG, L=MYCITY, S=MYSTATE, C=MY"
create the client certificate
keytool -export -alias clientkeys -keystore client.keystore -storepass 123456 -file client.cer
Now, import the server certificate to the client trust store.
keytool -import -alias serverCert -keystore client.truststore -storepass clientcert -file server.cer
now load the client keystore as mentioned in erickson's comment in the link provided by Werner.
Let me know if things are still not clear. But I suggest you read some documentation on google related to SSL Handshaking between a client and a server.
来源:https://stackoverflow.com/questions/13015910/using-self-signed-certificate-in-java