https 인터페이스 로 인증 서 를 돌아 갑 니 다.

7956 단어 자바
package com.llw.medical.isc.util;

import com.alibaba.fastjson.JSONObject;
import com.llw.medical.common.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;


public class HttpsUtil1 {
    private static Logger logger = LoggerFactory.getLogger(HttpsUtil1.class);


    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    public static String sendHtpps(String url,Map paramMap,String method,String cookie) {
        String result = "";
        BufferedReader in = null;
        HttpURLConnection conn;
        InputStream inputStream = null;
        OutputStreamWriter out = null;
        try {
            trustAllHosts();
            URL realUrl = new URL(url);
            //             (http   https)
            if (realUrl.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            //          
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //   POST          
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod(method);
            if(StringUtils.isNotEmpty(cookie)){
                conn.setRequestProperty("Cookie", cookie);
            }

            if(paramMap != null && !paramMap.isEmpty()){
                out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // utf-8  
                out.append(JSONObject.toJSONString(paramMap));
                out.flush();
                out.close();
            }

            conn.connect();
            if( conn.getResponseCode() == 200){
                inputStream = conn.getInputStream();
                String ck = conn.getHeaderField("Set-Cookie");
                System.out.println("cookie:"+ck);
            }else{
                inputStream = conn.getErrorStream();
            }

            in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("https request error:" + e);

        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }


    public static String getCookie(String url) {
        String cookie = "";
        String result = "";
        BufferedReader in = null;
        HttpURLConnection conn;
        InputStream inputStream = null;
        OutputStreamWriter out = null;
        Map paramMap = new HashMap();
        paramMap.put("userName", "11");
        paramMap.put("password", "11@123");
        paramMap.put("serverIp", "192.168.11.1");
        paramMap.put("serverPort", "1111");
        try {
            trustAllHosts();
            URL realUrl = new URL(url);
            //             (http   https)
            if (realUrl.getProtocol().toLowerCase().equals("https")) {
                HttpsURLConnection https = (HttpsURLConnection) realUrl.openConnection();
                https.setHostnameVerifier(DO_NOT_VERIFY);
                conn = https;
            } else {
                conn = (HttpURLConnection) realUrl.openConnection();
            }
            //          
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            //   POST          
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8"); // utf-8  
            out.append(JSONObject.toJSONString(paramMap));
            out.flush();
            out.close();
            conn.connect();
            if( conn.getResponseCode() == 200){
                inputStream = conn.getInputStream();
                 cookie = conn.getHeaderField("Set-Cookie");
            }else{
                inputStream = conn.getErrorStream();
            }

            in = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }

            logger.info("      {}",result);
            if(StringUtils.isNotEmpty(result)){
                JSONObject responseObject = JSONObject.parseObject(result);
                int resultCode = (int) responseObject.get("resultCode");
                if(resultCode == 0){
                    return cookie;
                }else{
                    return null;
                }
            }else{
                return "";
            }
        } catch (Exception e) {
            logger.info("https request error:" + e);

        } finally {//   finally       、   
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return cookie;
    }

    private static void trustAllHosts() {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[] {};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        } };
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {
        HttpsUtil.sendHtpps("https://*/device/devicelist/2/1/100",null,"GET","JSESSIONID=2252611B290B769DB8EAD5D23940F1E7FA7671261EC2E1CFCB65F61C5BF71E48; Path=/; Secure; HttpOnly");
    }
}

좋은 웹페이지 즐겨찾기