java https安全传输
HttpsURLConnection 扩展 HttpURLConnection,支持各种特定于 https 功能。此类使用 HostnameVerifier 和 SSLSocketFactory。为这两个类都定义了默认实现。但是,可以根据每个类(静态的)或每个实例来替换该实现。所有新 HttpsURLConnection 实例在创建时将被分配“默认的”静态值,通过在连接前调用每个实例适当的 set 方法可以重写这些值
在URL前加https://前缀表明是用SSL加密的。 你的电脑与服务器之间收发的信息传输将更加安全。
Web服务器启用SSL需要获得一个服务器证书并将该证书与要使用SSL的服务器绑定。
http和https使用的是完全不同的连接方式,用的端口也不一样,前者是80,后者是443。http的连接很简单,是无状态的,...
HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、身份认证的网络协议
要比http协议安全
[java]
import java.io.*;
import java.net.*;
import java.security.*;
import java.security.cert.*;
import javax.net.ssl.*;
public class HttpsURLConnectionTest {
private String url = "<A href="http://127.0.0.1:8080/TestWeb/version">https://127.0.0.1:8080/TestWeb/version</A>";
private myX509TrustManager xtm = new myX509TrustManager();
private myHostnameVerifier hnv = new myHostnameVerifier();
public HttpsURLConnectionTest() {
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("TLS"); //或SSL
X509TrustManager[] xtmArray = new X509TrustManager[] {xtm};
sslContext.init(null, xtmArray, new java.security.SecureRandom());
} catch (GeneralSecurityException e) {
e.printStackTrace();
}
if (sslContext != null) {
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}
HttpsURLConnection.setDefaultHostnameVerifier(hnv);
}
public void run() {
HttpsURLConnection urlCon = null;
try {
urlCon = (HttpsURLConnection)(new URL(url)).openConnection();
urlCon.setDoOutput(true);
urlCon.setRequestMethod("POST");
urlCon.setRequestProperty("Content-Length", "1024");
urlCon.setUseCaches(false);
urlCon.setDoInput(true);
urlCon.getOutputStream().write("Data={\"type\":\"P003\"}".getBytes("gbk"));
urlCon.getOutputStream().flush();
urlCon.getOutputStream().close();
BufferedReader in = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
// 增加自己的代码
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
HttpsURLConnectionTest httpsTest = new HttpsURLConnectionTest();
httpsTest.run();
}
}
/** *//**
* 重写三个方法
* @author Administrator
*
*/
class myX509TrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] chain, String authType) {
}
public void checkServerTrusted(X509Certificate[] chain, String authType) {
System.out.println("cert: " + chain[0].toString() + ", authType: " + authType);
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
/** *//**
* 重写一个方法
* @author Administrator
*
*/
class myHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
System.out.println("Warning: URL Host: " + hostname + " vs. " + session.getPeerHost());
return true;
}
}
补充:综合编程 , 安全编程 ,