jdk1.7 不支持TLS1.2解决方案

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

class HttpTest {
    public static void main(String[]args) throws Exception{

        SSLContext sslcontext=SSLContext.getInstance("TLSv1.2");
        sslcontext.init(null,null,null);
        URL serverUrl = new URL("https://api.sxxx.com/onlinepay/quickPay");
        HttpsURLConnection conn =(HttpsURLConnection) serverUrl.openConnection();
       conn.setSSLSocketFactory(sslcontext.getSocketFactory());
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        //必须设置false,否则会自动redirect到重定向后的地址
       
conn.setInstanceFollowRedirects(false);
        conn.connect();
        String result = getReturn(conn);
        System.out.println(result);
    }

    /*请求url获取返回的内容*/
   
public static StringgetReturn(HttpsURLConnection connection) throws IOException {
        StringBuffer buffer = new StringBuffer();
        //将返回的输入流转换成字符串
       
try(InputStreaminputStream = connection.getInputStream();
            InputStreamReaderinputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader= new BufferedReader(inputStreamReader);){
            String str = null;
            while ((str =bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            String result =buffer.toString();
            return result;
        }
    }

}

发表评论 / Comment

用心评论~