Java 7 HTTPS POST 请求示例:使用 TLSv1.2 协议
以下是一个使用 Java 7 进行 HTTPS POST 请求的示例,使用 TLSv1.2 协议版本:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
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;
public class HttpsPostExample {
public static void main(String[] args) throws Exception {
String url = 'https://example.com/api';
Map<String, String> params = new HashMap<String, String>();
params.put('name', 'John');
params.put('age', '30');
sendPostRequest(url, params);
}
private static void sendPostRequest(String url, Map<String, String> params) throws Exception {
// Disable SSL certificate validation
disableSslVerification();
// Create connection
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// Set request method
con.setRequestMethod('POST');
// Set TLS version to 1.2
con.setSSLSocketFactory(getSslContext().getSocketFactory());
con.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
// Set request headers
con.setRequestProperty('Content-Type', 'application/x-www-form-urlencoded');
// Build request body
StringBuilder requestBody = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (requestBody.length() > 0) {
requestBody.append('&');
}
requestBody.append(entry.getKey());
requestBody.append('=');
requestBody.append(entry.getValue());
}
// Send request
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(requestBody.toString().getBytes());
os.flush();
os.close();
// Get response
int responseCode = con.getResponseCode();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Print response
System.out.println('Response code: ' + responseCode);
System.out.println('Response body: ' + response.toString());
}
private static SSLContext getSslContext() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance('TLSv1.2');
sslContext.init(null, getTrustManagers(), new SecureRandom());
return sslContext;
}
private static TrustManager[] getTrustManagers() {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
}
};
return trustAllCerts;
}
private static void disableSslVerification() throws NoSuchAlgorithmException, KeyManagementException {
TrustManager[] trustAllCerts = getTrustManagers();
SSLContext sslContext = SSLContext.getInstance('TLSv1.2');
sslContext.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
}
}
请注意,由于 Java 7 不支持 TLSv1.3,因此在此示例中使用了 TLSv1.2。如果您使用的是 Java 11 或更高版本,建议使用 TLSv1.3 作为协议版本。
原文地址: https://www.cveoy.top/t/topic/mR2m 著作权归作者所有。请勿转载和采集!