代码集锦 - smile0821/learngit GitHub Wiki

  1. 创建一个异步线程,不管返回值 @SuppressWarnings("rawtypes") CompletableFuture insertDataSource = CompletableFuture.runAsync(() -> { try { dataSourceRepository.save(dataSource); } catch (Exception e) { LOGGER.error("insertDataSource error:" + e.getMessage()); } }, ThreadCachedPoolUtils.getFixedExecutorService()); CompletableFuture.allOf(insertDataSource).join();
  2. 创建异步线程,要求等待返回值

CompletableFuture c = CompletableFuture.runAsync(() -> { try { updateWp(saasCode, userId, randomLogID, oprMOs, tableMap, dataMap, tranPara); } catch (MoException e) { logger.error("updateWp error."); } }, ThreadCachedPoolUtils.getFixedExecutorService()); CompletableFuture insertBp = CompletableFuture.runAsync(() -> { try { insertBp(saasCode, userId, randomLogID, tableMap, dataMap); } catch (MoException e) { logger.error("insertBp error."); } }, ThreadCachedPoolUtils.getFixedExecutorService()); CompletableFuture.allOf(insertBp,updateWp).join();

3.select页签可编辑 function clearSelect(obj,e){ opt = obj.options[0]; opt.selected = "selected"; //使用退格(backspace)键实现逐字删除的编辑功能 if((e.keyCode== 8) ||(e.charCode==8)){ opt.value = opt.value.substring(0, opt.value.length>0?opt.value.length-1:0); opt.text = opt.value; } //使用删除(Delete)键实现逐字删除的编辑功能 if((e.keyCode== 46) ||(e.charCode==46)){ opt.value = ""; opt.text = opt.value; } //还可以实现其他按键的响应 document.addEventListener('paste', function (evt) { var clipdata = evt.clipboardData || window.clipboardData; var clipboard_data = clipdata.getData('text/plain')||clipdata.getData('text'); //console.log("paste value" + clipboard_data); if((e.ctrlKey && e.keyCode==86)){ if(clipboard_data!=undefined){ opt.value = clipboard_data; opt.text = opt.value; } } }); }

4.跳过ssl验证

package com.yeahmobi.billing.util;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;

public class SslUtil {
	
	public static CloseableHttpClient sslHttpClientBuild() {
		Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", trustAllHttpsCertificates()).build();
		//创建ConnectionManager,添加Connection配置信息
		PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(connectionManager).build();
		return httpClient;
	}
	
	private static SSLConnectionSocketFactory trustAllHttpsCertificates() {
		SSLConnectionSocketFactory socketFactory = null;
		TrustManager[] trustAllCerts = new TrustManager[1];
		TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		SSLContext sc = null;
		try {
			sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, null);
			socketFactory = new SSLConnectionSocketFactory(sc, NoopHostnameVerifier.INSTANCE);
			// HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		return socketFactory;
	}
	
	static class miTM implements TrustManager, X509TrustManager {
		
		public X509Certificate[] getAcceptedIssuers() {
			return null;
		}
		
		public void checkServerTrusted(X509Certificate[] certs, String authType) {
			//don't check
		}
		
		public void checkClientTrusted(X509Certificate[] certs, String authType) {
			//don't check
		}
	}
	
}

5.http调用

package com.yeahmobi.billing.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.yeahmobi.framework.exception.BusinessLogicException;

public class HttpRequestUtil {
    public static void main(String[] args) throws FileNotFoundException, IOException, BusinessLogicException {
    	String url = String.format("http://10.12.13.36:38081/bundle/detail?productId=%s&attr=MainGenreInfo", "1494847131");
        String getResult = doGet(url, null, null);
        
        if (Strings.isNullOrEmpty(getResult)) {
  	      throw new RuntimeException("request ymservice empty response");
  	    }

  	    JSONObject object = JSONObject.parseObject(getResult);
  	    if (null == object) {
  	    	throw new RuntimeException("request ymservice response can't be parsed");
  	    }
  	    if(!StringUtil.equals(object.getString("message"), "success")) {
  	    	String errorInfo = String.format("response error,code:%d,error:%s",object.getInteger("code"),object.getString("error"));
  	    	throw new RuntimeException(errorInfo);
  	    }else {
  	    	
  	    	JSONObject jsonObject = object.getJSONObject("data");
  	    	String name = jsonObject.getString("MainGenreInfo");
  	    	JSONObject a = JSONObject.parseObject(name);
  	    	System.out.println(a.getString("name"));
  	    }
       
//        System.out.println("getResult:"+(new Gson().toJson(response.getData())));
    }

    public static String doGet(String url,Map<String,String> headerMap, Map<String,String> requestParam) throws BusinessLogicException  {
//		CloseableHttpClient httpClient = HttpClients.createDefault();
    	CloseableHttpClient httpClient = SslUtil.sslHttpClientBuild();
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000) // 设置连接超时时间
				.setConnectionRequestTimeout(5000) // 设置请求超时时间
				.setSocketTimeout(5000).setRedirectsEnabled(true)// 默认允许自动重定向
				.build();
		HttpGet httpGet = new HttpGet(url);
		httpGet.setConfig(requestConfig);
		// 设置请求头
		if(headerMap!=null){
			for(Map.Entry<String, String> header:headerMap.entrySet()){
				httpGet.addHeader(header.getKey(), header.getValue());
			}
		}
		String result = "";
		try {
			HttpResponse httpResponse = httpClient.execute(httpGet);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				// 获得返回的结果
				result = EntityUtils.toString(httpResponse.getEntity());
			} 
		} catch (IOException e) {
			throw new BusinessLogicException(e.getLocalizedMessage());
		} finally {
			try {
				httpClient.close();
			} catch (IOException e) {
				throw new BusinessLogicException(e.getLocalizedMessage());
			}
		}
		return result;
    }
    
    public static String uploadFilePost(String url, Map<String,String> headerMap, Map<String,List<File>> fileMap,
    		Map<String,String> formDataParam) throws BusinessLogicException  {
        String requestJson = "";
        //传入参数可以为file或者filePath,在此处做转换

//        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpClient httpClient = SslUtil.sslHttpClientBuild();
        
        CloseableHttpResponse httpResponse = null;
        try {
            HttpPost httppost = new HttpPost(url);
            // 设置超时时间5h
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(18000000).setConnectionRequestTimeout(18000000)
            		           .setSocketTimeout(18000000).build();
            httppost.setConfig(requestConfig);
            // 设置请求头
            if(headerMap!=null){
            	for(Map.Entry<String, String> header:headerMap.entrySet()){
            		httppost.addHeader(header.getKey(), header.getValue());
            	}
            }
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            //设置浏览器兼容模式
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //设置请求的编码格式
            builder.setCharset(Consts.UTF_8);
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            //添加文件
            if(fileMap!=null){
            	for(Map.Entry<String,List<File>> fileEntry:fileMap.entrySet()){
            		for (File file : fileEntry.getValue()) {
            			builder.addBinaryBody(fileEntry.getKey(), file);
            		}
            	}
            }
            // 设置form-data文本
            for(Map.Entry<String,String> param:formDataParam.entrySet()){
            	builder.addTextBody(param.getKey(), param.getValue());
            }
            HttpEntity reqEntity = builder.build();
            httppost.setEntity(reqEntity);

            httpResponse = httpClient.execute(httppost);
            int backCode = httpResponse.getStatusLine().getStatusCode();
            if(backCode == HttpStatus.SC_OK){
                HttpEntity httpEntity = httpResponse.getEntity();
                byte[] json= EntityUtils.toByteArray(httpEntity);
                requestJson = new String(json, "UTF-8");
                //关闭流
                EntityUtils.consume(httpEntity);
                return requestJson;
            }
        } catch (Exception e) {
        	throw new BusinessLogicException(e.getLocalizedMessage());
        }finally {
            //释放资源
            try {
                httpClient.close();
                httpResponse.close();
            } catch (IOException e) {
            	throw new BusinessLogicException(e.getLocalizedMessage());
            }

        }
        return null;
    }

}
⚠️ **GitHub.com Fallback** ⚠️