java访问https接口、发送数据、接收数据
1.建立连接
1 URL url = new URL(urlStr); 2 //创建SSLContext对象,并使用我们指定的信任管理器初始化 3 TrustManager[] tm = {new MyX509TrustManager ()}; 4 //SSLContext.getInstance(arg0, arg1),注意arg0要与要访问的https接口网站所用的TLS/SSL的版本一致,否则在打开连接时会报握手失败的错 5 SSLContext sslContext =SSLContext.getInstance("TLSv1.2","SunJSSE"); 6 sslContext.init(null, tm, new java.security.SecureRandom()); 7 //从上述SSLContext对象中得到SSLSocketFactory对象 8 SSLSocketFactory ssf = sslContext.getSocketFactory(); 9 //创建HttpsURLConnection对象,并设置其SSLSocketFactory对象 10 HttpsURLConnection urlCon = (HttpsURLConnection)url.openConnection(); 11 urlCon.setSSLSocketFactory(ssf);
2.向https接口发送数据
String str = "xxx";//你要发送的数据 byte[] reqData = str.getBytes(); urlCon.setDoOutput(true); urlCon.setDoInput(true); urlCon.setUseCaches(false); urlCon.setRequestProperty("Content-Type", "text/xml;charset=utf-8"); urlCon.setRequestProperty("Content-length", String.valueOf(reqData.length));
DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
printout.write(reqData);
printout.flush();
printout.close();
3.接收https接口返回的数据
1 DataInputStream input = null; 2 java.io.ByteArrayOutputStream out = null; 3 input = new DataInputStream(urlCon.getInputStream()); 4 out = new java.io.ByteArrayOutputStream(); 5 byte[] bufferByte = new byte[256]; 6 int l = -1; 7 int downloadSize = 0; 8 while ((l = input.read(bufferByte)) > -1) { 9 downloadSize += l; 10 out.write(bufferByte, 0, l); 11 out.flush(); 12 } 13 String resData = out.toString();