当前位置: 首页 > 工具软件 > bitcoin-core > 使用案例 >

java调用bitcoin的JSON-PRC

郑锦
2023-12-01
1:通过SSLSocketFactory和HttpsURLConnection调用
参见azazar的bitcoin.jsonrpcclient
环境:JDK1.7 
依赖:openssl 生成的server.cert和server.pem
导入server.cert到java keystore
1A:JKS
keytool -import -alias aliasName -v -file C:\..\server.cert -keystore  C:\..\jks.keystore -storepass pwd     
keytool -list -v -keystore C:\..\jks.keystore -storepass pwd

1B: HostnameVerifier:不检查证书的CN和请求的hostname是否一致
      public   static  HostnameVerifier createHostnameVerifier() {
         return   new  HostnameVerifier() {
                    @Override
                    public   boolean  verify(String paramString, SSLSession paramSSLSession) {
                          return   true ;
                  }
            };
    }
1C: SSLSocketFactory  
      public   static  SSLSocketFactory createSslSocketFactory(String JKSPath,String JKSPwd)  throws  Exception {
      KeyStore keyStore = KeyStore. getInstance(  "JKS" );
        // TODO  need to be changed into real path in linux
            keyStore.load(  new  FileInputStream(JKSPath), JKSPwd.toCharArray());
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(  "SunX509" );
            tmf.init(keyStore);
            SSLContext ctx = SSLContext. getInstance(  "TLS" );
            ctx.init(  null , tmf.getTrustManagers(),  null );
            SSLSocketFactory sslSocketFactory2 = ctx.getSocketFactory();
         return  sslSocketFactory2;
    }
1D:使用
              if  (conn  instanceof  HttpsURLConnection) {
                 if  (  hostnameVerifier  !=  null )
                    ((HttpsURLConnection)conn).setHostnameVerifier( hostnameVerifier  );
                 if  (  sslSocketFactory  !=  null ){
                        ((HttpsURLConnection)conn).setSSLSocketFactory(  sslSocketFactory );
                }
                  
            }
1E: 入参的 包装和解析bitcoin的响应JSON请查看源码 com.azazar.bitcoin.jsonrpcclient. BitcoinJSONRPCClient.query
2:通过HttpClient调用,simple JSON解析
环境:JDK1.7 httpclient-4.3.4.jar httpcore-4.3.2.jar
依赖:openssl 生成的server.cert和server.pem
2B:
        public   static  LayeredConnectionSocketFactory createSSLFactory(String JKSPath, String JKSPwd)
                    throws  Exception {
            KeyStore trustStore = KeyStore. getInstance(  "JKS" );
            FileInputStream instream =  new  FileInputStream(  new  File(JKSPath));
              try  {
                  trustStore.load(instream, JKSPwd.toCharArray());
            }  finally  {
                  instream.close();
            }
              // Trust own CA and all self-signed certs
            SSLContext sslcontext = SSLContexts. custom()
                        .loadTrustMaterial(trustStore,  new  TrustSelfSignedStrategy()).build();
              // Allow TLSv1 protocol only
            SSLConnectionSocketFactory sslsf =  new  SSLConnectionSocketFactory(sslcontext,
                          new  String[] {  "TLSv1"  },  null ,
                        SSLConnectionSocketFactory.  ALLOW_ALL_HOSTNAME_VERIFIER  );
              return  sslsf;
      }
2C: org.apache.http.impl.client.HttpClients
            CloseableHttpClient httpclient;
              try  {
                  httpclient = HttpClients.custom().setSSLSocketFactory( createSSLFactory( jksPath  jksPwd )).build();
            }  catch  (Exception e1) {
                  httpclient = HttpClientBuilder. create().build();
                  e1.printStackTrace();
            }
            HttpHost targetHost =  new  HttpHost(  host port "https"  );
            JSONObject json =  new  JSONObject();
            json.put(  "id" , id);
            json.put(  "method" , method);
              if  (!CollectionUtils. isEmpty(params)) {
                  JSONArray array =  new  JSONArray();
                  array.addAll(params);
                  json.put(  "params" , params);
            }
            JSONObject responseJsonObj =  null ;
              try  {
                  CredentialsProvider credsProvider =  new  BasicCredentialsProvider();
                  credsProvider.setCredentials(  new  AuthScope(  host port ),
                                new  UsernamePasswordCredentials(  rpcuser rpcpwd ));
                    // Create AuthCache instance
                  AuthCache authCache =  new  BasicAuthCache();
                    // Generate BASIC scheme object and add it to the local auth cache
                  BasicScheme basicAuth =  new  BasicScheme();
                  authCache.put(targetHost, basicAuth);
                    // Add AuthCache to the execution context
                  HttpClientContext context = HttpClientContext.create();
                  context.setCredentialsProvider(credsProvider);
                  context.setAuthCache(authCache);
                  HttpPost httppost =  new  HttpPost(  url );
                  StringEntity myEntity =  new  StringEntity(json.toJSONString());
                  httppost.setEntity(myEntity);
                  CloseableHttpResponse response = httpclient.execute(targetHost, httppost, context);
                  HttpEntity entity = response.getEntity();

 类似资料: