Przeglądaj źródła

跳过SSL验证

yaoyu 1 rok temu
rodzic
commit
abc4e6c582
1 zmienionych plików z 114 dodań i 51 usunięć
  1. 114 51
      pu/pu/src/private/nc/impl/th/ThOcrServiceImpl.java

+ 114 - 51
pu/pu/src/private/nc/impl/th/ThOcrServiceImpl.java

@@ -1,5 +1,11 @@
 package nc.impl.th;
 
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManager;
+import javax.net.ssl.X509TrustManager;
+import javax.net.ssl.SSLSession;
 import java.io.BufferedOutputStream;
 import java.io.BufferedReader;
 import java.io.ByteArrayOutputStream;
@@ -10,18 +16,19 @@ import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.InputStreamReader;
+import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.net.HttpURLConnection;
 import java.net.URL;
-import java.text.SimpleDateFormat;
+import java.security.Security;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
 import java.util.ArrayList;
-import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.UUID;
 import java.io.FileOutputStream;
-
 import nc.bs.dao.BaseDAO;
 import nc.bs.dao.DAOException;
 import nc.bs.framework.common.InvocationInfoProxy;
@@ -41,11 +48,6 @@ import nc.bs.pub.filesystem.IFileSystemService;
 import nc.itf.uap.IVOPersistence;
 
 import org.apache.commons.codec.digest.DigestUtils;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.methods.PostMethod;
-import org.apache.commons.httpclient.methods.RequestEntity;
-import org.apache.commons.httpclient.methods.StringRequestEntity;
-import org.bouncycastle.jce.provider.symmetric.Skipjack.Mac;
 
 import com.alibaba.fastjson.JSONArray;
 import com.alibaba.fastjson.JSONObject;
@@ -96,7 +98,7 @@ public class ThOcrServiceImpl implements IThOcrService{
 		//redis中获取用户token
 		String userToken ="";
 		 try {
-			  userToken = RedisTokenManager.getToken(billmaker); 
+			 userToken = RedisTokenManager.getToken(billmaker); 
 		  }catch(Exception e){
 			  // Redis 连接异常,执行相应的异常处理操作
 			  e.printStackTrace();
@@ -198,39 +200,43 @@ public class ThOcrServiceImpl implements IThOcrService{
 		insert(vos);
 	}
 	public String getOcrToken(String userid)  throws Exception{
-    	HttpClient httpClient = new HttpClient();
-    	httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
-        httpClient.getHttpConnectionManager().getParams().setSoTimeout(60000);
-        PostMethod postMethod = new PostMethod(buildToken);
-        postMethod.setRequestHeader("content-type", "application/json");
-        postMethod.setRequestHeader("appkey", appId);
-        Map<String,String> oamap = QueryOAUserid(userid);
+		initSSL();  
+	    URL url = new URL(buildToken);
+        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+        connection.setConnectTimeout(60000);
+        connection.setReadTimeout(60000);
+        connection.setRequestMethod("POST");
+        connection.setRequestProperty("Content-Type", "application/json");
+        connection.setRequestProperty("appkey", appId);
         long l = System.currentTimeMillis();
+        Map<String,String> oamap = QueryOAUserid(userid);
         Map<String, Object> map = new HashMap<String, Object>();
         map.put("role", 1);
         map.put("name", oamap.get("lastname"));
-        map.put("userId", oamap.get("id"));//OA用户体系的用户id 2108
+        map.put("userId", oamap.get("id"));
         map.put("cid", cid);
         String s1 = JSONObject.toJSONString(map);
         String s2 = s1 + "&time=" + l + "&secret="+secret;
         byte[] requestBodyBytes = s2.getBytes("UTF-8");
         String newMd5 = DigestUtils.md5Hex(requestBodyBytes);
         String s4 = s1 + "&time=" + l + "&md5=" + newMd5;
-        RequestEntity entity = new StringRequestEntity (s4 ,"application/json" ,"UTF-8");
-        postMethod.setRequestEntity(entity);
-        httpClient.executeMethod(postMethod);
-		String responseMsg = postMethod.getResponseBodyAsString().trim();
-		//返回结果{"data":"WEAPPe8Ke9pFzz9fbZ3qCcN6itq1zLHCKOgPmXHz6uIg8eOg","actionMsg":{"code":0,"message":"执行成功"}}
- //       System.out.println("返回结果"+ responseMsg);
-
-		 JSONObject json = JSONObject.parseObject(responseMsg);
-		 String token=json.getString("data");
-		 String status=json.getString("status");
-		 //保存token返回值到日志文件里
-		 NcLog.info("token:"+token);
-		 
-		 if(token == null){
-			 throw new BusinessException(responseMsg);
+        connection.setDoOutput(true);
+        OutputStream outputStream = connection.getOutputStream();
+        outputStream.write(s4.getBytes("UTF-8"));
+        outputStream.flush();
+        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
+        StringBuilder response = new StringBuilder();
+        String inputLine;
+        while ((inputLine = in.readLine()) != null) {
+            response.append(inputLine);
+        }
+        in.close();
+        JSONObject json = JSONObject.parseObject(response.toString());
+        NcLog.info("token:"+json.toString());
+        String token = json.getString("data");
+        
+        if(token == null){
+			 throw new BusinessException(json.toString());
 		 }
 		 
 		 return token;
@@ -245,6 +251,7 @@ public class ThOcrServiceImpl implements IThOcrService{
 		 String LINEND = "\r\n";
 		 String boundary = UUID.randomUUID().toString();
 		 FileInputStream fileInputStream = new FileInputStream(file);
+		 initSSL();
 	     URL url = new URL(uploadUrl);
 	     HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
 	     httpURLConnection.setDoInput(true);
@@ -305,6 +312,7 @@ public class ThOcrServiceImpl implements IThOcrService{
 	        BufferedReader br = null;
 	        String result = "";
 	        try {
+	        	initSSL();
 	        	URL url = new URL(pathUrl);
 	        	//打开和url之间的连接
 	            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
@@ -703,7 +711,7 @@ public class ThOcrServiceImpl implements IThOcrService{
 		        return fileNames;
 		    }
 
-
+		    
 		@Override
 		public void UpdateInvoiceStatus(String status, InvoiceVO[] vos) throws Exception {
 			//T提交——1  S收回——0  //Y审批通过——2 //R驳回
@@ -843,27 +851,39 @@ public class ThOcrServiceImpl implements IThOcrService{
 			}
 		}
 		
-		/**
-		 * 
-		 * @param content
-		 * @throws Exception
+		/*
+		 * 发票锁定
 		 */
 		private String UpdateInvoiceOCR(String bodyJson) throws Exception {
 			String content =  InvoiceCloudAESUtil.startAssemble(aesKey, secret, bodyJson);
-			HttpClient httpClient = new HttpClient();
-	        PostMethod postMethod = new PostMethod(ec_comm);
-	        postMethod.setRequestHeader("content-type", "application/json");
-	        postMethod.setRequestHeader("appkey", appId);
-	        RequestEntity entity = new StringRequestEntity (content ,"application/json" ,"UTF-8");
-	        postMethod.setRequestEntity(entity);
-	        httpClient.executeMethod(postMethod);
-			String responseMsg = postMethod.getResponseBodyAsString().trim();
-			JSONObject json = JSONObject.parseObject(responseMsg);
-			String data=json.getString("data");
-			if(data == null) {
-				 throw new BusinessException(responseMsg);
-			}
-			return json.toJSONString();
+			initSSL();
+	        URL url = new URL(ec_comm);
+	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
+	        connection.setRequestMethod("POST");
+	        connection.setRequestProperty("content-type", "application/json");
+	        connection.setRequestProperty("appkey", appId);
+	        connection.setDoOutput(true);
+	        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
+	        wr.writeBytes(content);
+	        wr.flush();
+	        wr.close();
+	        int responseCode = connection.getResponseCode();
+	        if (responseCode != 200) {
+	            throw new Exception("HTTP Error: " + responseCode);
+	        }
+	        StringBuilder response = new StringBuilder();
+	        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
+	        String inputLine;
+	        while ((inputLine = in.readLine()) != null) {
+	            response.append(inputLine);
+	        }
+	        in.close();
+	        JSONObject jsonResponse = JSONObject.parseObject(response.toString());
+	        String data = jsonResponse.getString("data");
+	        if (data == null) {
+	            throw new BusinessException(response.toString());
+	        }
+	        return jsonResponse.toString();
 		}
 		
 		
@@ -942,6 +962,9 @@ public class ThOcrServiceImpl implements IThOcrService{
 		}
 		
 		
+		/*
+		 * 查询OA信息
+		 */
 		private Map<String,String> QueryOAUserid(String cuserid) throws Exception {
 			StringBuffer sql = new StringBuffer();
 			sql.append("SELECT");
@@ -958,4 +981,44 @@ public class ThOcrServiceImpl implements IThOcrService{
 			}
 			return map;
 		}
+		
+	
+		/*
+		 * 跳过SSL
+		 */
+		private  void initSSL() throws Exception {
+			System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");  
+	        Security.setProperty("ssl.SocketFactory.provider", "");  
+	        Security.setProperty("ssl.ServerSocketFactory.provider", "");  
+	  
+	        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {  
+	            @Override  
+	            public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
+	                return null;  
+	            }  
+	  
+	            @Override  
+	            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
+	            }  
+	  
+	            @Override  
+	            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {  
+	            }  
+	        }  
+	        };  
+	  
+	        SSLContext sc = SSLContext.getInstance("TLS");  
+	        sc.init(null, trustAllCerts, new java.security.SecureRandom());  
+	        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());  
+	  
+	        HostnameVerifier allHostsValid = new HostnameVerifier(){  
+	            @Override  
+	            public boolean verify(String hostname, SSLSession session) {  
+	                return true;  
+	            }  
+	        };  
+	        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);  
+		}
+	
+		
 }