Java中后台通过Post方式连接HTTPS获取返回的值

很多时候,我们要通过Java中的jsse来发送post请求给https,然后获取返回的值.

下面就是一个可以使用的源码.这个直接复制过去,自己添加一些参数就可以使用了.

import java.io.*;
import java.net.*;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.*;

public class Https_link3 {

public static void main(String[] args) throws Exception {
String url="https://........";

//加入需要传递的参数

//编码方式

}

}


private static class TrustAnyTrustManager implements X509TrustManager {


public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}


public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}


public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}


private static class TrustAnyHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}

/**
* post方式请求服务器(https协议)
* @param url
*            请求地址
* @param content
*            参数
* @param charset
*            编码
* @return
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
* @throws IOException
*/
public static byte[] post(String url, String content, String charset)
           throws NoSuchAlgorithmException, KeyManagementException,
           IOException {
       SSLContext sc = SSLContext.getInstance("SSL");
       sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
               new java.security.SecureRandom());
 
       URL console = new URL(url);
       HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
       conn.setSSLSocketFactory(sc.getSocketFactory());
       conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
       conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
       conn.connect();
       DataOutputStream out = new DataOutputStream(conn.getOutputStream());
       out.write(content.getBytes(charset));
       // 刷新、关闭
       out.flush();
       out.close();
       InputStream is = conn.getInputStream();
       if (is != null) {
           ByteArrayOutputStream outStream = new ByteArrayOutputStream();
           byte[] buffer = new byte[1024];
           int len = 0;
           while ((len = is.read(buffer)) != -1) {
               outStream.write(buffer, 0, len);
           }
           is.close();
           return outStream.toByteArray();
       }
     
       return null;
}


}


你可能感兴趣的:(网络知识,Https,java加密)