当前位置: 代码网 > it编程>编程语言>Java > java 用httpClient 根据ca.crt、client.crt和client.key文件实现与服务端https通讯

java 用httpClient 根据ca.crt、client.crt和client.key文件实现与服务端https通讯

2024年08月01日 Java 我要评论
重要的来了,有人不知道哪里lisenyuan 这个字符串是怎么来的。以上没什么就直接帖代码就行。执行上面命令设置就行了。




    public static sslconnectionsocketfactory getsslsocktetbidirectional() throws exception {
        sslconnectionsocketfactory sslsf = null;

        try{
// ca certificate is used to authenticate server
            string linuxlocalip = ipdatautils.getselfpublicip();
            //正式环境代码,配置正常逻辑代码
          
            certificatefactory caf = certificatefactory.getinstance("x.509");
            fileinputstream cain = new fileinputstream(ca_path);
            x509certificate ca = (x509certificate) caf.generatecertificate(cain);
            keystore caks = keystore.getinstance("jks");
            caks.load(null, null);
            //caks.setcertificateentry("ca-certificate", ca);
            caks.setcertificateentry("verify", ca);
            trustmanagerfactory tmf = trustmanagerfactory.getinstance("pkix");
            tmf.init(caks);
// client key and certificates are sent to server so it can authenticate us
            certificatefactory cf = certificatefactory.getinstance("x.509");
            fileinputstream crtin = new fileinputstream(crt_path);
            x509certificate cacert = (x509certificate) cf.generatecertificate(crtin);
            crtin.close();

            keystore ks = keystore.getinstance(keystore.getdefaulttype());
            ks.load(null, null);
            ks.setcertificateentry("certificate", cacert);
            ks.setkeyentry("private-key", getprivatekey(key_path), password.tochararray(), new java.security.cert.certificate[] { cacert });
            keymanagerfactory kmf = keymanagerfactory.getinstance("pkix");
            kmf.init(ks, password.tochararray());
// finally, create ssl socket factory
            sslcontext context = sslcontext.getinstance("tlsv1.2");
            context.init(kmf.getkeymanagers(), tmf.gettrustmanagers(), new securerandom());

            sslsf = new sslconnectionsocketfactory(context,null, null,noophostnameverifier.instance);
        }catch (exception e){
            system.out.println("证书加载失败");
            e.printstacktrace();
        }

        return sslsf;
    }




  private static privatekey getprivatekey(string path) throws exception {
//byte[] buffer = base64.getdecoder().decode(getpem(path));
// base64 base64 = new base64();
       
        base64decoder base64decoder = new base64decoder();
        byte[] buffer = base64decoder.decodebuffer(getpem(path));
        base64decoder decoder = new base64decoder();
        //byte[] buffer = decoder.decodebuffer(getpem(path));
        //pkcs8encodedkeyspec keyspec = new pkcs8encodedkeyspec(base64.decodebase64(getpem(path)));

      /*  pkcs8encodedkeyspec keyspec = new pkcs8encodedkeyspec(buffer);
        keyfactory keyfactory = keyfactory.getinstance("ec");
        privatekey privatekey = keyfactory.generateprivate(keyspec);
        return privatekey;*/

        pkcs8encodedkeyspec keyspec = new pkcs8encodedkeyspec(buffer);
        keyfactory keyfactory = keyfactory.getinstance("rsa");
        return keyfactory.generateprivate(keyspec);
    }





private static string getpem(string path) throws exception {
        fileinputstream fin = new fileinputstream(path);
        bufferedreader br = new bufferedreader(new inputstreamreader(fin));
        string readline = null;
        stringbuilder sb = new stringbuilder();
        while ((readline = br.readline()) != null) {
            if (readline.charat(0) == '-') {
                continue;
            } else {
                sb.append(readline);
                sb.append('\r');
            }
        }
        fin.close();
        return sb.tostring();
    }

以上没什么就直接帖代码就行

接下来

  
   public static  string ca_path = "c:/users/lsy/desktop/certs/ca.crt";
    public static  string crt_path = "c:/users/lsy/desktop/certs/client.crt";
    public static  string key_path = "c:/users/lsy/desktop/certs/client.key";
    public static  string password = "lisenyuan";

 public static string httppost( list<shengxinfiledatavm> list) throws ioexception {
        closeablehttpclient httpclient = null;
        list<shengxindataadd> listdata=new arraylist();
        jsonobject jsonobject = new jsonobject();
      /* map map=new hashmap<>();*/
        shengxindataadd shengxindataadd=new shengxindataadd();
        stringbuffer sb1=new stringbuffer();
        stringbuffer sb2=new stringbuffer();
        string linuxlocalip = ipdatautils.getselfpublicip();
        string igip=null;


        for (int i = 0; i < list.size(); i++) {

            shengxinfiledata shengxinfiledata1 = list.get(i);
            sb1.append(shengxinfiledata1.getsequencingnumber());
            sb1.append(",");
            sb2.append(shengxinfiledata1.getspecimenname());
            sb2.append(",");

        }
        shengxindataadd.setsequencingnumber(sb1.substring(0,sb1.length()-1));
        shengxindataadd.setspecimenname(sb2.substring(0,sb2.length()-1));
        shengxindataadd.settaskid(list.get(0).gettaskid().tostring());
        shengxindataadd.setprojectnumber(list.get(0).getprojectnumber());
        shengxindataadd.setpanelnumber(list.get(0).getpanel());
        shengxindataadd.setfiletype(list.get(0).getfiletype());
        shengxindataadd.setcontractnumber(list.get(0).getcontractnumber());
        shengxindataadd.setcallback(igip);
        string stringjson = json.tojsonstring(shengxindataadd);
        string result = null;
       // system.out.println("请求数据:"+jsonobject.tojsonstring());
        system.out.println("请求数据:"+stringjson);

        try{
            sslconnectionsocketfactory sslsf = getsslsocktetbidirectional();
//设置认证信息到httpclient
            httpclient = httpclients.custom().setsslsocketfactory(sslsf).build();
        }catch (exception e){
            system.out.println("证书读取失败");
            e.printstacktrace();
            return "证书读取失败";

        }
// 根据默认超时限制初始化requestconfig
        requestconfig requestconfig = requestconfig.custom().setsockettimeout(25000).setconnecttimeout(25000).build();
//post通讯初始化
        httppost httppost = new httppost("https:");
// 设置报文头 得指明使用utf-8编码,否则到api服务器xml的中文不能被成功识别
        httppost.addheader("content-type", "application/x-www-form-urlencoded; charset=utf-8");
/*        httppost.addheader("igip", igip);*/
//添加请求报文体
        stringentity reqentity = new stringentity(stringjson, "utf-8");
        httppost.setentity(reqentity);
// 设置请求器的配置
        httppost.setconfig(requestconfig);
        try {
            closeablehttpresponse response = null;
            inputstream reqin = null;
            try {
//打印请求报文体
                reqin = httppost.getentity().getcontent();
                string reqbbody = streamutils.copytostring(reqin, standardcharsets.utf_8);
                system.out.println("请求数据:"+reqbbody);
//与服务端通讯
                response = httpclient.execute(httppost);

//打印通讯状态
                system.out.println(jsonobject.tojsonstring(response.getstatusline()));
                jsonobject.tojsonstring(response.getstatusline());

                httpentity entity = response.getentity();
                inputstream in = null;
                try {

                    in = entity.getcontent();
                    string rspbbody = streamutils.copytostring(in, standardcharsets.utf_8);
                    system.out.println("应答为:"+rspbbody);
                    in.close();

                    if(response.getstatusline().getstatuscode()==200){
                        result="成功";
                    }else{
                        result="失敗";
                    }

// result = entityutils.tostring(entity, "utf-8");


                } catch (ioexception e) {
                    system.out.println("服务端应答信息读取失败");
                    e.printstacktrace();
                    return "服务端应答信息读取失败";
                }finally {
                    if (in !=null){
                        in.close();
                    }
                }

            } catch (ioexception e) {
                system.out.println("与服务端通讯失败");
                e.printstacktrace();
                return "与服务端通讯失败";
            }finally {
                try{
                //释放资源
                    if (httpclient != null){
                        httpclient.close();
                    }
                    if (response != null){
                        response.close();
                    }
                    if (reqin != null){
                        reqin.close();
                    }
                }catch (ioexception e) {
                    e.printstacktrace();
                }
            }

        } finally {
            httppost.abort();
        }
        return result;

    }

重要的来了,有人不知道哪里lisenyuan 这个字符串是怎么来的

keytool -import -alias mycert -keystore cacerts -file c:/users/lsy/desktop/certs/ca.crt

执行上面命令设置就行了

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com