java https post request and ignore the certificate, the parameters on the body

New java class 1, with the role certificate is bypassed

package cn.smartercampus.core.util;
import java.security.cert.CertificateException;  
import java.security.cert.X509Certificate;  
  
import javax.net.ssl.X509TrustManager; 
public class MyX509TrustManager implements X509TrustManager {  
	  
    public void checkClientTrusted(X509Certificate[] chain, String authType)  
            throws CertificateException {  
    }  
  
    public void checkServerTrusted(X509Certificate[] chain, String authType)  
            throws CertificateException {  
    }  
  
    public X509Certificate[] getAcceptedIssuers() {  
        return null;  
    }  
}

  

2 https post request

Package cn.smartercampus.core.util; 


Import in javax.net.ssl *. ;
 Import the javax.servlet.http.HttpServletRequest; 

Import org.apache.commons.lang.StringUtils; 

Import the java.io. * ;
 Import the java.net. the HttpURLConnection;
 Import the java.net.URL;
 Import java.net.URLEncoder;
 Import of java.security.cert.X509Certificate;
 Import the java.util.HashMap;
 Import a java.util.Map; 

public  class HttpsPostUtil {
     // add the host name validator class, the host is not set to verify 
    Private  Final  static= DO_NOT_VERIFY the HostnameVerifier new new the HostnameVerifier () {
         public  Boolean Verify (String hostname, the SSLSession the session) {
             return  to true ; 
        } 
    }; 

    // add a trusted host 
    Private  static  void trustAllHosts () {
         // create the chain does not validate the certificate used herein, the trust manager x509 certificate is 
        a TrustManager [] = trustAllCerts new new a TrustManager [] { new new MyX509TrustManager () {
             public of java.security.cert.X509Certificate [] getAcceptedIssuers () {
                 return  new new of java.security.cert.X509Certificate [] {}; 
            } 

            public void CheckClientTrusted (the X509Certificate [] catena alberghiera, the authType String) { 
            } 

            public  void checkServerTrusted (the X509Certificate [] catena alberghiera, the authType String) { 
            } 
        }}; 
        // install all the trust manager trust 
        the try { 
            the SSLContext SC = SSLContext.getInstance ( "the TLS " ); 
            sc.init ( null , trustAllCerts, new new java.security.SecureRandom ());
             // an HttpsURLConnection SSLSocket by establishing a secure connection with HTTPS, SSLSocket SSLSocketFactory generated by the object. 
            HttpsURLConnection.setDefaultSSLSocketFactory (sc.getSocketFactory ());
        } The catch (Exception E) { 
            e.printStackTrace (); 
        }
    }

    /**
     *  发送post 数据
     * @param urls
     * @return
     */
    public static String heart(String urls, String param, String contentType, String method) {
        StringBuffer sb=new StringBuffer();
        DataOutputStream out = null;
        BufferedReader responseReader = null;
        InputStream in1 = null;
        try {
            trustAllHosts();
            //Creating resources url 
            the URL of url = new newThe URL of (urls);
             // establish connection http 
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection (); 
            conn.setHostnameVerifier (DO_NOT_VERIFY); 
            // set without buffering 
            conn.setUseCaches ( false );
             // setting allows output 
            conn.setDoOutput ( to true );
             // set enable input 
            conn.setDoInput ( to true );
             // set the transfer mode 
            conn.setRequestMethod (Method);
             // System.out.println (conn.getRequestMethod ());
             // set to maintain a long connection
            conn.setRequestProperty ( "Connection", "the Keep-Alive" );
             // Set Character Set File: 
            conn.setRequestProperty ( "the Charset", "UTF-. 8" );
             // convert a byte array
 //             byte [] Data = (param) .getBytes ();
 //             // set file length
 //             conn.setRequestProperty ( "the Content-the length", String.valueOf (data.length));
             // set the file type: 
            conn.setRequestProperty ( "the Content -Type " , contentType); 
            conn.setRequestProperty ( " the Authorization " , param);
             // start the connection request 
            conn.connect(); 
            OUT = new new the DataOutputStream (conn.getOutputStream ());
             // write request string 
            out.writeBytes (param); 
            out.flush (); 

            // System.out.println (conn.getResponseCode ( )); 

            // request returns the status 
            IF (HttpURLConnection.HTTP_OK == conn.getResponseCode ()) { 
                System.out.println ( "connection successful" );
                 // request to return data 
                IN1 = conn.getInputStream (); 
                String the readLine; 
                responseReader = new new the BufferedReader ( new new InputStreamReader(in1));
                while((readLine=responseReader.readLine()) != null){
                    sb.append(readLine).append("\n");
                }
            } else {
                System.out.println("error++");
            }
        } catch (Exception e) {

        } finally {
            try {
                if (null != responseReader)
                    responseReader.close();
                if (null != in1)
                    in1.close();
            } catch(Exception e) {}
            try {
                out.close();
            } catch(Exception e) {}
        }

        return sb.toString();

    }
    
    /**
     *  发送post 数据
     * @param urls
     * @return
     */
    public static String sendPost(String urls, String param, String contentType, String method) {
        StringBuffer sb=new StringBuffer();
        DataOutputStream out = null; 
        BufferedReader responseReader = null ; 
        InputStream IN1 = null ;
         the try { 
            trustAllHosts (); 
            // create resources url 
            the URL of url = new new the URL of (urls);
             // establish connection http 
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection (); 
            conn. setHostnameVerifier (DO_NOT_VERIFY); 
            // set without buffering 
            conn.setUseCaches ( to false );
             // set the allowable output 
            conn.setDoOutput ( to true);
             // set enable input 
            conn.setDoInput ( to true );
             // set the transfer mode 
            conn.setRequestMethod (Method);
             // System.out.println (conn.getRequestMethod ());
             // set to maintain a long connection 
            conn.setRequestProperty ( "Connection", "the Keep-Alive" );
             // set character set file: 
            conn.setRequestProperty ( "the charset", "UTF-. 8" );
             // convert a byte array
 //             byte [] = Data (param ) .getBytes ();
 //             // set file length
 //            conn.setRequestProperty ( "the Content-the Length", String.valueOf (data.length));
             // set the file type: 
            conn.setRequestProperty ( "the Type-the Content" , contentType);
             // start connection request 
            conn.connect (); 
            OUT = new new the DataOutputStream (conn.getOutputStream ());
             // write request string 
            out.writeBytes (param); 
            out.flush (); 

            // System.out.println (conn.getResponseCode ()); 

            // request returns the status 
            IF (HttpURLConnection.HTTP_OK == conn.getResponseCode ()) { 
                System.out.println ( "connection successful");
                // 请求返回的数据
                in1 = conn.getInputStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while((readLine=responseReader.readLine()) != null){
                    sb.append(readLine).append("\n");
                }
            } else {
                System.out.println("error++");
            }
        } catch (Exception e) {

        } finally {
            try {
                if (null != responseReader)
                    responseReader.close();
                if (null != in1)
                    in1.close();
            } catch(Exception e) {}
            try {
                out.close();
            } catch(Exception e) {}
        }

        return sb.toString();

    }

    /**
     * map转url参数
     */
    public static String map2Url(Map<String, String> paramToMap) {
        if (null == paramToMap || paramToMap.isEmpty()) {
            return null;
        }
        StringBuffer url  = new StringBuffer();
        boolean      isfist = true;
        for (Map.Entry<String, String> entry : paramToMap.entrySet()) {
            if (isfist) {
                isfist = false;
            } else {
                url.append("&");
            }
            url.append(entry.getKey()).append("=");
            String value = entry.getValue();
            if (!StringUtils.isEmpty(value)) {
                url.append(value);
            }
        }
        return url.toString();
    }
    
    public static void main(String[] args) {
        System.out.println("123");
        Map<String, String> params = new HashMap<String, String>();
        params.put("client_id", "xx.cn");
        params.put("client_secret", "UY83SNFJWLU32NJSLJIK");
        params.put("code", "40ce7f41d6562e47dbdc33593ddce1b46444cdb93514b3aaced7be90eb51a16f");
        params.put("grant_type", "authorization_code");
        params.put("redirect_uri", "xxn/index.jsp");
        //要发送的POST请求url?Key=Value&amp;Key2=Value2&amp;Key3=Value3的形式
        //application/json;charset=UTF-8  application/x-www-form-urlencoded;charset=UTF-8
        String sb = sendPost("https://id.pdedu.sh.cn/connect/token",map2Url(params),"application/x-www-form-urlencoded;charset=UTF-8","POST");
        //System.out.println(sb);
        
        
    }
   

    
}

 

Guess you like

Origin www.cnblogs.com/remember-forget/p/11978328.html