java calls https interface

Keywords: Programming SSL Java network JSON

Difference between http and https

https protocol needs to apply for certificate from ca, generally there are few free certificates, so it needs a certain fee.
http is hypertext transmission protocol, information is plaintext transmission, and https is ssl encrypted transmission protocol with security.
http and https use totally different connection methods and different ports. The former is 80 and the latter is 443.
The connection of http is very simple and stateless; HTTPS protocol is a network protocol constructed by SSL+HTTP protocol that can carry out encrypted transmission and identity authentication, which is safer than http protocol.

Call method and step (skip certificate method is used here)

MyX509TrustManager class

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.X509TrustManager;

public class MyX509TrustManager implements X509TrustManager{

	@Override
	public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		// TODO Auto-generated method stub
		
	}

	@Override
	public X509Certificate[] getAcceptedIssuers() {
		// TODO Auto-generated method stub
		return null;
	}

}

HttpRequest class, only post request is implemented here

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

public class HttpRequest {
	public static String sendPost(String url, String param) {
		 PrintWriter out = null;
	     BufferedReader in = null;
	     String result = "";
	     try {
	    	 // Create the SSLContext object and initialize it with the trust manager we specified     
	    	 TrustManager[] tm = { new MyX509TrustManager() }; 
	    	 SSLContext sslContext = SSLContext.getInstance("SSL");
	    	 sslContext.init(null, tm, new java.security.SecureRandom());
	    	 
	    	// Get the SSLSocketFactory object from the SSLContext object above     
	         SSLSocketFactory ssf = sslContext.getSocketFactory(); 
	    	// Open connection to URL
	    	URL realUrl = new URL(url);
	    	HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
	    	conn.setSSLSocketFactory(ssf);
	    	// Set common request properties
	    	conn.setRequestProperty("accept", "*/*");
	    	conn.setRequestProperty("connection", "Keep-Alive");
	    	conn.setRequestProperty("content-Type", "application/json");
	    	conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	    	// To send a POST request, you must set the following two lines
	    	conn.setDoOutput(true);
	    	conn.setDoInput(true);
	    	// Get the output stream corresponding to URLConnection object
	    	out = new PrintWriter(conn.getOutputStream());
	    	// Send request parameters
	    	out.print(param);
	    	// Buffer of flush output stream
	    	out.flush();
	    	// Define BufferedReader input stream to read response of URL
	    	in = new BufferedReader(
	    	new InputStreamReader(conn.getInputStream()));
	    	String line;
	    	 while ((line = in.readLine()) != null) {
	    		 result += line;
	    	}
	    	System.out.println("-----result-----"+result);
	    	} catch (Exception e) {
	    		e.printStackTrace();	
	    	} finally {// Use finally block to close output flow and input flow
                try {
                    if (out != null) {
                        out.close();
                    }
                    if (in != null) {
                        in.close();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
	     	return result;
	   }
}

Test class

public class Test {
	public static void main(String[] args){ 
        String url = "Access address";
        Map<String,Object> param = new HashMap<String,Object>();
	    param.put("parameter", "value");
	    String message = JSONUtils.toJSONString(param);
        String str = HttpRequest.sendPost(url, message);
        System.out.println(str);
	}
}

Posted by LearningKid on Fri, 01 Nov 2019 15:38:23 -0700