httpClient忽略https的证书认证

忽略https证书认证代码:

 /**
     * 创建模拟客户端(针对 https 客户端禁用 SSL 验证)
     * @return
     * @throws Exception
     */
    public static CloseableHttpClient createHttpClientWithNoSsl() throws Exception {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        // don't check
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        // don't check
                    }
                }
        };

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, trustAllCerts, null);
        LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx);
        return HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();
    }

一、Get请求

接口地址及参数:https://xxx.xxx.com/api/v3/technicians?input_data={“list_info”:{“search_fields”:{“email_id”:“wjjia@iflytek.com”}}}

postman调用示例:

在这里插入图片描述

java代码实现:

OAPropUtil.technician_info_url = https://xxx.xxx.com/api/v3/technicians

String url = OAPropUtil.technician_info_url+"?input_data="+ URLEncoder.encode(JSON.toJSONString(listInfo),"UTF-8");

headerMap.put("authtoken", "12345");
            headerMap.put("Content-type", "application/json;charset=UTF-8");
            String resultStr = OAUtil.getWithHeaderIgnoreSSL(url,headerMap);
  
  public static String getWithHeaderIgnoreSSL(String url,Map<String, String> headerMap) throws Exception {
        CloseableHttpClient httpclient = createHttpClientWithNoSsl();
        HttpGet get = new HttpGet(url);
        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                get.addHeader(key, headerMap.get(key));
            }
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
                .setSocketTimeout(20000).setConnectTimeout(3000).build();
        get.setConfig(requestConfig);
        HttpResponse response = httpclient.execute(get);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                //4.解析响应,获取数据
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity,"UTF-8");
                } else {
                    System.out.println("statusCode[" + statusCode + "],url[" + url + "]");
                }
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        }
        return null;
    }          

post示例一:
在这里插入图片描述

Map<String, String> param = new HashMap<>();
                            param.put("input_data", JSON.toJSONString(request));
                            Map<String,String> itsmHeader = new HashMap<>();
                            itsmHeader.put("authtoken", "12345");
                            itsmHeader.put("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
                            
 String ticketStr = OAUtil.postWithHeaderIgnoreSSL(url, param, itsmHeader);

 public static String postWithHeaderIgnoreSSL(String url, Map<String,String> param, Map<String, String> headerMap) throws Exception {
        CloseableHttpClient httpclient = createHttpClientWithNoSsl();
        HttpPost post = new HttpPost(url);
        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                post.addHeader(key, headerMap.get(key));
            }
        }
        List<org.apache.http.NameValuePair> nameValuePairList = new ArrayList<>();
        if (param != null) {
            for (String key : param.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, param.get(key)));
            }
        }
        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
                    .setSocketTimeout(20000).setConnectTimeout(3000).build();
            post.setConfig(requestConfig);

            HttpEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
            //设置请求参数
            post.setEntity(entity);
            HttpResponse response = httpclient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            String res = EntityUtils.toString(response.getEntity(),"UTF-8");
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED){
                //返回json格式
                post.releaseConnection();
                return res;
            } else {
                System.out.println("response《" + res + "》,url[" + url + "],json[" + param + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (post != null)
                post.releaseConnection();
            if (httpclient != null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

HttpClient工具类范例

/*
 *
 * Copyright (C) 1999-2012 IFLYTEK Inc.All Rights Reserved.
 *
 * FileName:OAUtil.java
 *
 * Description:
 *
 * History:
 * Version   Author      Date            Operation
 * 1.0	  jfzhao   2014年11月4日上午10:41:12	       Create
 */
package com.iflytek.oa.util;

import com.alibaba.fastjson.JSON;
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.ssl.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import weaver.system.code.CodeBuild;
import weaver.workflow.request.RequestManager;

import javax.net.ssl.*;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @author jfzhao
 * @version 1.0
 */
public class OAUtil {
    /**
     * @param s oa内存储的EASID
     * @return easID
     * @description 由于OA不允许人员直接挂靠在公司下,
     * 所以原EAS中直接挂靠公司的人员归属的部门EASID为EAS公司ID加other字样构成
     * @author jfzhao
     * @create 2014年11月4日上午10:45:23
     * @version 1.0
     */
    public static String subEASID(String s) {
        if (s.endsWith("other")) {
            return s.substring(0, s.length() - "other".length());
        } else {
            return s;
        }
    }

    /**
     * @param requestManager 请求对象
     * @description 创建单据编码
     * @author jfzhao
     * @create 2014年12月4日下午4:16:54
     * @version 1.0
     */
    public static void createNumber(RequestManager requestManager) {
        int formID = requestManager.getFormid();
        int isBill = requestManager.getIsbill();
        int workFlowID = requestManager.getWorkflowid();
        int creater = requestManager.getCreater();
        int requestID = requestManager.getRequestid();
        int createrType = requestManager.getCreatertype();
        CodeBuild cbuild = new CodeBuild(formID, String.valueOf(isBill),
                workFlowID, creater, createrType);
        cbuild.getFlowCodeStr(requestID, isBill, formID, workFlowID, creater,
                createrType);
    }

    /**
     * @param url        地址
     * @param valuePairs 参数
     * @return 返回的信息
     * @throws Exception 异常信息
     * @description post方法
     * @author zhsong
     * @create 2015年11月2日下午4:21:43
     * @version 1.0
     */
    public static String post(String url, NameValuePair[] valuePairs) throws Exception {
        HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        PostMethod postMethod = new UTF8PostMethod(url);
        postMethod.setRequestBody(valuePairs);
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒) 
        managerParams.setConnectionTimeout(3000);
        managerParams.setSoTimeout(35000);
        try {
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } finally {
            //20181119 添加释放连接
            postMethod.releaseConnection();
        }
        return null;
    }

    public static String authorizationPost(String token, String url, NameValuePair[] valuePairs) throws Exception {
        HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        PostMethod postMethod = new UTF8PostMethod(url);
        postMethod.setRequestBody(valuePairs);
        postMethod.setRequestHeader("token", token);
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(3000);
        managerParams.setSoTimeout(35000);
        try {
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } finally {
            //20181119 添加释放连接
            postMethod.releaseConnection();
        }
        return null;
    }

    public static class UTF8PostMethod extends PostMethod {
        public UTF8PostMethod(String url) {
            super(url);
        }

        @Override
        public String getRequestCharSet() {
            return "UTF-8";
        }
    }

    /**
     * @param url
     * @param valuePairs
     * @return
     * @throws Exception
     * @desc get方式
     * @author chaozhou6
     * @date 2018年3月27日 下午10:31:10
     */
    public static String get(String url, NameValuePair[] valuePairs) throws Exception {

        String params = nameValuePairToString(valuePairs);
        HttpClient httpclient = new HttpClient();
        GetMethod getMethod = new UTF8GetMethod(url + "?" + params);
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒) 
        managerParams.setConnectionTimeout(3000);
        // 设置返回超时时间(单位毫秒)
        managerParams.setSoTimeout(35000);
        try {
            int statusCode = httpclient.executeMethod(getMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return getMethod.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        }
        return null;
    }

    public static String get(String url) throws Exception {
        HttpClient httpclient = new HttpClient();
        GetMethod getMethod = new UTF8GetMethod(url);
        getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(3000);
        // 设置返回超时时间(单位毫秒)
        managerParams.setSoTimeout(20000);
        try {
            int statusCode = httpclient.executeMethod(getMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return getMethod.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        }
        return null;
    }

    /**
     * @param valuePairs
     * @return
     * @desc NameValuePair转为get方式参数
     * @author chaozhou6
     * @date 2018年3月27日 下午11:09:45
     */
    private static String nameValuePairToString(NameValuePair[] valuePairs) {
        String params = "";
        if (valuePairs != null && valuePairs.length > 0) {
            for (NameValuePair nameValuePair : valuePairs) {
                params += nameValuePair.getName() + "=" + nameValuePair.getValue() + "&";
            }
            params = params.substring(0, params.length() - 1);
        }
        return params;
    }

    public static class UTF8GetMethod extends GetMethod {
        public UTF8GetMethod(String url) {
            super(url);
        }

        @Override
        public String getRequestCharSet() {
            return "UTF-8";
        }
    }

    /**
     * @param logtype
     * @return
     * @description oa nodetype对应汉字说明
     * @author zhsong
     * @create 2016年3月23日上午9:38:53
     * @version 1.0
     */
    public static String getHandle(String logtype) {
        if (null != logtype && !"".equals(logtype)) {
            String ret = "";
            char[] ch = logtype.toCharArray();
            if (ch != null && ch.length == 1) {
                char t = logtype.toCharArray()[0];
                switch (t) {
                    case '0':
                        ret = "批准";
                        break;
                    case '1':
                        ret = "保存";
                        break;
                    case '2':
                        ret = "提交";
                        break;
                    case '3':
                        ret = "退回";
                        break;
                    case '4':
                        ret = "重新打开";
                        break;
                    case '5':
                        ret = "删除";
                        break;
                    case '6':
                        ret = "激活";
                        break;
                    case '7':
                        ret = "转发";
                        break;
                    case '9':
                        ret = "批注";
                        break;
                    case 'e':
                        ret = "强制归档";
                        break;
                    case 't':
                        ret = "抄送";
                        break;
                    case 's':
                        ret = "督办";
                        break;
                    default:
                        ret = "";
                        break;
                }
            }
            return ret;
        }
        return null;
    }

    /**
     * @param htmlStr
     * @return
     * @description 过滤
     * @author lqxiong
     * @create 2016年11月23日上午9:42:36
     * @version 1.0
     */
    public static String delHTMLTag(String htmlStr) {
        if (null == htmlStr) {
            return "";
        }
        String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式
        String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式
        String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
        String regEx_space = "\\s*|\t|\r|\n";// 定义空格回车换行符

        Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
        Matcher m_script = p_script.matcher(htmlStr);
        htmlStr = m_script.replaceAll(""); // 过滤script标签

        Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
        Matcher m_style = p_style.matcher(htmlStr);
        htmlStr = m_style.replaceAll(""); // 过滤style标签

        Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
        Matcher m_html = p_html.matcher(htmlStr);
        htmlStr = m_html.replaceAll(""); // 过滤html标签

        Pattern p_space = Pattern.compile(regEx_space, Pattern.CASE_INSENSITIVE);
        Matcher m_space = p_space.matcher(htmlStr);
        htmlStr = m_space.replaceAll(""); // 过滤空格回车换行符

        htmlStr = htmlStr.replaceAll("&nbsp;", " ");

        // 返回文本字符串
        return htmlStr.trim();
    }

    /**
     * desc OA远程调用接口方法
     * author mhhuang2
     *
     * @param url            接口地址
     * @param nameValuePairs 接口参数
     * @return
     * @throws
     * @date 2017年6月5日 下午3:36:50
     */
    public static String remoteInvoke(String url, NameValuePair[] nameValuePairs) {
        String result = null;
        try {
            result = post(url, nameValuePairs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (null != result) {
            result = result.trim();
        }
        return result;
    }

    /**
     * @param authenticationCode (new sun.misc.BASE64Encoder()).encode("用户名:密码".getBytes())
     * @param url                访问地址
     * @param jsonContent        json串
     * @return
     * @description 基于HttpClient的Basic认证方案的Patch请求方式
     * @author ckyang
     * @create 2017年6月21日上午10:46:08
     * @version 1.0
     */
    public static Map<String, String> BasicAuthorizationPatch(String authenticationCode, String url, String jsonContent) {
        Map<String, String> map = new HashMap<String, String>();
        String responseResult = "";
        String exceptionMessage = "";
        int statusCode = 404;

        HttpClient httpClient = new HttpClient();
        PostMethod method = new UTF8PostMethod(url);

//		RequestEntity requestEntity = new StringRequestEntity(text); //中文乱码

        RequestEntity requestEntity = null;

        try {
            requestEntity = new StringRequestEntity(jsonContent, "application/vnd.oracle.adf.resourceitem+json", "UTF-8");
//			requestEntity = new StringRequestEntity(jsonContent, "application/vnd.oracle.adf.resourceitem+json", "iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        method.setRequestEntity(requestEntity);

        method.setRequestHeader("x-http-method-override", "PATCH"); //patch方式访问需要加这个设置,post访问方式不加这个设置
        //application/vnd.oracle.adf.action+json
        //application/vnd.oracle.adf.resourceitem+json
//		method.setRequestHeader("Content-Type","application/vnd.oracle.adf.action+json");
        method.setRequestHeader("Content-Type", "application/vnd.oracle.adf.resourceitem+json");
        //用户名密码:YANGHONGBO:Hand1234
//		method.setRequestHeader("Authorization", " Basic " + (new sun.misc.BASE64Encoder()).encode("YANGHONGBO:Hand1234".getBytes()));
        method.setRequestHeader("Authorization", " Basic " + authenticationCode);

        try {
            statusCode = httpClient.executeMethod(method);
            //responseResult = method.getResponseBodyAsString(); //中文乱码

            String charset = "UTF-8";
            InputStream ins = method.getResponseBodyAsStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(ins, charset)); //按指定的字符集构建文件流
            StringBuffer sbf = new StringBuffer();
            String line = "";
            while ((line = br.readLine()) != null) {
                sbf.append(line);
            }
            br.close();

            responseResult = sbf.toString().trim();
        } catch (Exception e) {
            exceptionMessage = e.getMessage();
            e.printStackTrace();
        }

        map.put("responseResult", responseResult);
        map.put("exceptionMessage", exceptionMessage);
        map.put("statusCode", statusCode + "");
        map.put("statusText", HttpStatus.getStatusText(statusCode));

        return map;
    }

    /**
     * @param authStr  OA调用CRM接口认证用户名/参数
     * @param destUrl  访问地址
     * @param postData soap串
     * @return
     * @description 通过soap方式传输数据
     * @author lqxiong
     * @create 2017年8月9日16:46:33
     * @version 1.0
     */
    public static Map<String, String> httpPost(String destUrl, String postData, String authStr) throws Exception {
        Map<String, String> response = new HashMap<String, String>();
        int responseCode = 404;
        String responseMessage = "网络异常";

        URL url = new URL(destUrl);
        HttpURLConnection.setFollowRedirects(true);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        if (null != conn) {
            conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
//        	conn.setFollowRedirects(true);
            conn.setAllowUserInteraction(false);
            conn.setRequestMethod("POST");

            //byte[] authBytes = authStr.getBytes("UTF-8");
            //String auth = com.sun.org.apache.xml.internal.security.utils.Base64.encode(authBytes);
            //conn.setRequestProperty("Authorization", "Basic " + auth);

            if (StringUtils.isNotBlank(authStr)) {
                conn.setRequestProperty("Authorization", "Basic " + authStr);
            }

            OutputStream out = conn.getOutputStream();
            OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
            writer.write(postData);
            writer.close();
            out.close();

            responseCode = conn.getResponseCode();
//        	System.out.println("connection status: " + conn.getResponseCode());
//        	System.out.println("connection response: " + conn.getResponseMessage());

            InputStream in = conn.getInputStream();
            InputStreamReader iReader = new InputStreamReader(in, "UTF-8");
            BufferedReader bReader = new BufferedReader(iReader);

            String line;
            responseMessage = "";
            while ((line = bReader.readLine()) != null) {
                responseMessage += line;
            }
            iReader.close();
            bReader.close();
            in.close();
            conn.disconnect();
        }

        response.put("responseCode", String.valueOf(responseCode));
        response.put("responseMessage", responseMessage);

        return response;
    }

    /**
     * @param url
     * @param json
     * @return
     * @desc post方式
     * @author chaozhou6
     * @date 2017年11月13日 上午10:34:22
     */
    public static String post(String url, String json) {
        HttpClient httpclient = new HttpClient();
        PostMethod postMethod = new UTF8PostMethod(url);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        try {
            HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(3000);
            managerParams.setSoTimeout(90000);
            RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }

    /**
     * 同步PS请求
     *
     * @param url
     * @param json
     * @return
     * @author junliang3
     * @date 2022/2/17 10:23
     */
    public static String postForPS(String url, String json) {
        HttpClient httpclient = new HttpClient();
        PostMethod postMethod = new UTF8PostMethod(url);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        try {
            HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(3000);
            managerParams.setSoTimeout(90000);
            RequestEntity requestEntity = new StringRequestEntity(json, "text/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }

    /**
     * @param token
     * @param url
     * @param json
     * @return
     * @description 向大E传递数据
     */
    public static String authorizationHttpPost(String token, String url, String json) {
        HttpClient httpClient = new HttpClient();
        PostMethod method = new UTF8PostMethod(url);
        try {
            HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(3000);
            managerParams.setSoTimeout(20000);

            RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
            method.setRequestEntity(requestEntity);
            method.setRequestHeader("Authorization", "Bearer  " + token);
            int statusCode = httpClient.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                return method.getResponseBodyAsString();
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return null;
    }

    public static String httpPostHead(String token, String url, String json) {
        HttpClient httpClient = new HttpClient();
        PostMethod method = new UTF8PostMethod(url);
        try {
            HttpConnectionManagerParams managerParams = httpClient.getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(3000);
            managerParams.setSoTimeout(20000);

            RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
            method.setRequestEntity(requestEntity);
            method.setRequestHeader("Authorization", token);
            int statusCode = httpClient.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                return method.getResponseBodyAsString();
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return null;
    }


    /**
     * @param url
     * @return
     * @description
     * @author lqxiong
     * @create 2018年7月11日下午6:06:36
     * @version 1.0
     */
    public static String post(String url) {
        try {
            HttpClient httpclient = new HttpClient();
            PostMethod postMethod = new UTF8PostMethod(url);

            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param workcode
     * @return
     * @desc 员工工号转换
     * @author chaozhou6
     * @date 2017年11月6日 下午12:22:26
     */
    public static String workcodeConversion(String workcode) {
        String workcodeTemp = "";
        workcodeTemp = workcode.replace("BD", "BEST");
        workcodeTemp = workcodeTemp.replace("JD", "WHJD");
        workcodeTemp = workcodeTemp.replace("BB", "BBXF");
        workcodeTemp = workcodeTemp.replace("BZ", "BZXF");
        workcodeTemp = workcodeTemp.replace("FY", "FYSM");
        workcodeTemp = workcodeTemp.replace("HB", "HBXF");
        workcodeTemp = workcodeTemp.replace("HN", "HNXF");
        workcodeTemp = workcodeTemp.replace("JL", "JLKX");
        workcodeTemp = workcodeTemp.replace("SZ", "SZXF");
        workcodeTemp = workcodeTemp.replace("XY", "XYXF");
        workcodeTemp = workcodeTemp.replace("JC", "XFJC");
        return workcodeTemp;
    }

    /**
     * @return
     * @description 将多个oaid按照域账号顺序排序
     * @author lqxiong
     * @create 2018年3月29日下午3:40:51
     * @version 1.0
     */
    public static String sortoaIds(String loginIds, Map<String, String> oaIdsMap) {
        String oaIds = "";
        if (StringUtils.isNotBlank(loginIds)) {
            String[] loginIdsArray = loginIds.split(",");
            if (null != oaIdsMap && !oaIdsMap.isEmpty()) {
                String temp = "";
                for (int i = 0; i < loginIdsArray.length; i++) {
                    //按照传入的域账号顺序,取出oaid
                    temp = loginIdsArray[i];
                    if (null != oaIdsMap.get(temp) && !oaIdsMap.get(temp).isEmpty()) {
                        oaIds += oaIdsMap.get(temp) + ",";
                    }
                }
                oaIds = oaIds.substring(0, oaIds.length() - 1);
            }
        }
        return oaIds;
    }

    /**
     * @param url
     * @param json
     * @return
     * @desc post方式
     * @author chaozhou6
     * @date 2017年11月13日 上午10:34:22
     */
    public static String postWithResultCharset(String url, String json) {
        HttpClient httpclient = new HttpClient();
        PostMethod postMethod = new UTF8PostMethod(url);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        try {
            HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(3000);
            managerParams.setSoTimeout(20000);
            RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }

    /**
     * @param url
     * @param valuePairs
     * @return
     * @throws Exception
     * @desc get方式
     * @author chaozhou6
     * @date 2018年3月27日 下午10:31:10
     */
    public static String getWithResultCharset(String url, NameValuePair[] valuePairs) throws Exception {

        String params = nameValuePairToString(valuePairs);
        HttpClient httpclient = new HttpClient();
        GetMethod getMethod = new UTF8GetMethod(url + "?" + params);
        getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(3000);
        try {
            int statusCode = httpclient.executeMethod(getMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return getMethod.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        }
        return null;
    }

    /**
     * get请求携带请求头
     *
     * @param url        地址
     * @param valuePairs 参数
     * @param headerMap  请求头信息
     * @return String
     * @throws Exception
     * @desc get方式
     * @author lewang4
     * @date 2021-12-03
     */
    public static String getWithHeader(String url, NameValuePair[] valuePairs, Map<String, String> headerMap) throws Exception {

        String params = nameValuePairToString(valuePairs);
        HttpClient httpclient = new HttpClient();
        GetMethod getMethod = new UTF8GetMethod(url + "?" + params);

        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                getMethod.setRequestHeader(key, headerMap.get(key));
            }
        }
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(3000);
        try {
            int statusCode = httpclient.executeMethod(getMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return getMethod.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        }
        return null;
    }

    /**
     * post方法
     *
     * @param url       地址
     * @param json      参数
     * @param headerMap 请求头信息
     * @return 返回的信息
     * @author zhsong
     * @create 2015年11月2日下午4:21:43
     */
    public static String postWithHeader(String url, String json, Map<String, String> headerMap) {
        HttpClient httpclient = new HttpClient();
        PostMethod postMethod = new UTF8PostMethod(url);

        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                postMethod.setRequestHeader(key, headerMap.get(key));
            }
        }

        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");

        try {
            HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(3000);
            managerParams.setSoTimeout(20000);
            RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }

    /**
     * 反写OTC系统
     *
     * @param url  地址
     * @param json 数据
     * @return string
     * @author junliang3
     * @date 2022/5/24 10:39
     */
    public static String postToOTC(String url, String json) {
        HttpClient httpclient = new HttpClient();
        PostMethod postMethod = new UTF8PostMethod(url);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        try {
            HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
            // 设置连接超时时间(单位毫秒)
            managerParams.setConnectionTimeout(3000);
            managerParams.setSoTimeout(90000);
            RequestEntity requestEntity = new StringRequestEntity(json, "application/json", "UTF-8");
            postMethod.setRequestEntity(requestEntity);
            postMethod.setRequestHeader("sign", OAPropUtil.contract_synOTC_sign);
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }

    /**
     * @param url        地址
     * @param valuePairs 参数
     * @return 返回的信息
     * @throws Exception 异常信息
     * @description post方法
     * @author zhsong
     * @create 2015年11月2日下午4:21:43
     * @version 1.0
     */
    public static String postToFF(String url, NameValuePair[] valuePairs) throws Exception {
        HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        PostMethod postMethod = new UTF8PostMethod(url);
        postMethod.setRequestBody(valuePairs);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(3000);
        managerParams.setSoTimeout(35000);
        try {
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } finally {
            //20181119 添加释放连接
            postMethod.releaseConnection();
        }
        return null;
    }

    public static String postToXF(String url, NameValuePair[] valuePairs) throws Exception {
        HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        PostMethod postMethod = new UTF8PostMethod(url);
        postMethod.setRequestBody(valuePairs);
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(3000);
        managerParams.setSoTimeout(35000);
        byte[] b = JSON.toJSONString(valuePairs).getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        RequestEntity requestEntity = new InputStreamRequestEntity(is, b.length,
                "text/xml; charset=utf-8");
        postMethod.setRequestEntity(requestEntity);
        try {
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } finally {
            //20181119 添加释放连接
            postMethod.releaseConnection();
        }
        return null;
    }

    /**
     * post请求携带请求头
     *
     * @param url        地址
     * @param valuePairs 参数
     * @param headerMap  请求头信息
     * @return String
     * @throws Exception
     * @desc post 方式
     * @author rfzhou3
     * @date 2022-12-19
     */
    public static String postWithHeader(String url, NameValuePair[] valuePairs, Map<String, String> headerMap) throws Exception {
        HttpClient httpclient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
        PostMethod postMethod = new OAUtil.UTF8PostMethod(url);
        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                postMethod.setRequestHeader(key, headerMap.get(key));
            }
        }
        postMethod.setRequestBody(valuePairs);
        HttpConnectionManagerParams managerParams = httpclient.getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(3000);
        managerParams.setSoTimeout(10000);
        try {
            int statusCode = httpclient.executeMethod(postMethod);
            if (statusCode == HttpStatus.SC_OK) {
                return postMethod.getResponseBodyAsString();
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } finally {
            postMethod.releaseConnection();
        }
        return null;
    }

    public static NameValuePair[] convertMap2NameValuePairs(Map<String, String> data) {
        Set<Map.Entry<String, String>> entrySet = data.entrySet();
        int size = entrySet.size();
        NameValuePair[] nameValuePairs = new NameValuePair[size];
        List<NameValuePair> nameValuePairList = new ArrayList<>();
        for (Map.Entry<String, String> entry : entrySet) {
            String key = entry.getKey();
            String value = entry.getValue();
            NameValuePair nameValuePair = new NameValuePair(key, value);
            nameValuePairList.add(nameValuePair);
        }
        for (int i = 0; i < nameValuePairList.size(); i++) {
            nameValuePairs[i] = nameValuePairList.get(i);
        }
        return nameValuePairs;
    }

    public static String getWithHeaderIgnoreSSL(String url,Map<String, String> headerMap) throws Exception {
        CloseableHttpClient httpclient = createHttpClientWithNoSsl();
        HttpGet get = new HttpGet(url);
        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                get.addHeader(key, headerMap.get(key));
            }
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
                .setSocketTimeout(20000).setConnectTimeout(3000).build();
        get.setConfig(requestConfig);
        HttpResponse response = httpclient.execute(get);
        try {
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                //4.解析响应,获取数据
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    return EntityUtils.toString(entity,"UTF-8");
                } else {
                    System.out.println("statusCode[" + statusCode + "],url[" + url + "]");
                }
            }
        } catch (HttpException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("网络异常!");
        }
        return null;
    }

    public static String postWithHeaderIgnoreSSL(String url, String json, Map<String, String> headerMap) throws Exception {
        CloseableHttpClient httpclient = createHttpClientWithNoSsl();
        HttpPost post = new HttpPost(url);
        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                post.addHeader(key, headerMap.get(key));
            }
        }
        post.setHeader("Content-type", "application/json;charset=utf-8");
        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
                    .setSocketTimeout(20000).setConnectTimeout(3000).build();
            post.setConfig(requestConfig);
            StringEntity s = new StringEntity(json,"UTF-8");
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpclient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK){
                //返回json格式
                String res = EntityUtils.toString(response.getEntity(),"UTF-8");
                post.releaseConnection();
                return res;
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (post != null)
                post.releaseConnection();
            if (httpclient != null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    public static String postIgnoreSSL(String url, String json, Map<String, String> headerMap) throws Exception {
        HttpClientBuilder builder = HttpClients.custom();
        builder.setSSLHostnameVerifier((hostName, sslSession) -> {
            return true; // 证书校验通过
        });
        CloseableHttpClient httpclient = builder.build();
        HttpPost post = new HttpPost(url);
        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                post.addHeader(key, headerMap.get(key));
            }
        }
        post.setHeader("Content-type", "application/json;charset=utf-8");
        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
                    .setSocketTimeout(20000).setConnectTimeout(3000).build();
            StringEntity s = new StringEntity(json,"UTF-8");
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/json");
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpclient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK){
                //返回json格式
                String res = EntityUtils.toString(response.getEntity(),"UTF-8");
                post.releaseConnection();
                return res;
            } else {
                System.out.println("statusCode[" + statusCode + "],url[" + url + "],json[" + json + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (post != null)
                post.releaseConnection();
            if (httpclient != null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 创建模拟客户端(针对 https 客户端禁用 SSL 验证)
     * @return
     * @throws Exception
     */
    public static CloseableHttpClient createHttpClientWithNoSsl() throws Exception {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    @Override
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        // don't check
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        // don't check
                    }
                }
        };

        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(null, trustAllCerts, null);
        LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(ctx);
        return HttpClients.custom()
                .setSSLSocketFactory(sslSocketFactory)
                .build();
    }

    /**
     * 跳过ssl验证 form表单提交
     * @param url /
     * @param param /
     * @param headerMap /
     * @return /
     * @throws Exception /
     */
    public static String postWithHeaderIgnoreSSL(String url, Map<String,String> param, Map<String, String> headerMap) throws Exception {
        CloseableHttpClient httpclient = createHttpClientWithNoSsl();
        HttpPost post = new HttpPost(url);
        // 设置请求头信息
        if (headerMap != null && headerMap.size() > 0) {
            for (String key : headerMap.keySet()) {
                post.addHeader(key, headerMap.get(key));
            }
        }
        List<org.apache.http.NameValuePair> nameValuePairList = new ArrayList<>();
        if (param != null) {
            for (String key : param.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, param.get(key)));
            }
        }
        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(1000)
                    .setSocketTimeout(20000).setConnectTimeout(3000).build();
            post.setConfig(requestConfig);

            HttpEntity entity = new UrlEncodedFormEntity(nameValuePairList, "UTF-8");
            //设置请求参数
            post.setEntity(entity);
            HttpResponse response = httpclient.execute(post);
            int statusCode = response.getStatusLine().getStatusCode();
            String res = EntityUtils.toString(response.getEntity(),"UTF-8");
            if (statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_CREATED){
                //返回json格式
                post.releaseConnection();
                return res;
            } else {
                System.out.println("response《" + res + "》,url[" + url + "],json[" + param + "]");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (post != null)
                post.releaseConnection();
            if (httpclient != null){
                try {
                    httpclient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/344692.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

软考复习之UML设计篇

UML统一建模语言 构件图&#xff1a;描述系统的物理结构&#xff0c;它可以用来显示程序代码如何分解成模块 部署图&#xff1a;描述系统中硬件和软件的物理结构&#xff0c;它描述构成系统架构的软件构件&#xff0c;处理器和设备 用例图&#xff1a;描述系统与外部系统及用…

C++读取txt文件中的逐个字符

为了增加读取的灵活性&#xff0c;所以separator和filename都设置为在主函数中获取输入或者在函数中传参的视线方法 举个例子&#xff0c;txt文件如下&#xff1a; household;2;true; 首先声明一个读取数据的文件 void read_data_file(const string& filename,char se…

【STM32】USB程序烧录需要重新上电 软件复位方法

文章目录 一、问题二、解决思路2.1 直接插拔USB2.2 给芯片复位 三、解决方法3.1 别人的解决方法3.2 在下载界面进行设置 一、问题 最近学习STM32的USB功能&#xff0c;主要是想要使用虚拟串口功能&#xff08;VCP&#xff09;&#xff0c;发现每次烧录之后都需要重新上电才可以…

训练模型时 遇到速度过慢时的深思 速度提升 (From GPU CPU)

训练模型时 遇到速度过慢时的深思 & 速度提升 GPU查看GPU使用情况 配置单机多卡并行训练torch.nn.DataParallel平衡DataParallel带来的显存使用不平衡的问题torch.nn.parallel.DistributedDataParallel 多机多gpu训练Reference 使用半精度训练更好的显卡&#xff0c;更轻的…

编译和链接---C语言

引言 众所周知&#xff0c;C语言是一门高级的编程语言&#xff0c;是无法被计算机直接读懂的&#xff0c;C语言也不同于汇编PHP&#xff0c;无法直接翻译成机器语言&#xff0c;在学习的过程中&#xff0c;你是否好奇过我们所敲的C语言代码&#xff0c;是如何一步步翻译成机器…

Docker容器引擎(1)

目录 一.Docker 概述 为什么要用到容器&#xff1f; docker是什么&#xff1f; 容器与虚拟机的区别&#xff1f; docker的三个核心概念&#xff1a; 二.安装docker 安装依赖包&#xff1a; 安装 Docker-CE并设置为开机自动启动&#xff1a; 查看 docker 版本信息&#…

10个常考的前端手写题,你全都会吗?(下)

前言 &#x1f4eb; 大家好&#xff0c;我是南木元元&#xff0c;热爱技术和分享&#xff0c;欢迎大家交流&#xff0c;一起学习进步&#xff01; &#x1f345; 个人主页&#xff1a;南木元元 今天接着上篇再来分享一下10个常见的JavaScript手写功能。 目录 1.实现继承 ES5继…

docker 部署springboot项目

新建Dockerfile ## AdoptOpenJDK 停止发布 OpenJDK 二进制&#xff0c;而 Eclipse Temurin 是它的延伸&#xff0c;提供更好的稳定性 ## 感谢复旦核博士的建议&#xff01;灰子哥&#xff0c;牛皮&#xff01; FROM eclipse-temurin:8-jre## 将后端项目的 Jar 文件&#xff0c…

软考复习之多媒体篇

常用的计算公式 数据传输率&#xff08;单位:b/s&#xff09; 未压缩的数据传输率 采样频率&#xff08;Hz&#xff09;* 量化位数&#xff08;位&#xff09;* 声道数 波形声音经过数字化后的信息数据量&#xff08;单位:字节&#xff09; 声音信号数据量 数据传输率 * …

简单实现网络编程

1. 前置知识 在学习网络编程前&#xff0c;我们需要先了解一些前置知识 1.1 客户端和服务器 在网络编程中&#xff0c;客户端和服务器是两个关键的角色。 客户端是发起连接并向服务器发送请求的一方。客户端通常是一个应用程序或设备&#xff0c;通过与服务器建立连接&…

白盒测试和黑盒测试的区别

黑盒测试 等价类划分 白盒测试 灰盒测试

K8S图像化工具rancher

Rancher是一个开源的企业级多集群的k8s管理平台 Rancher和k8s的区别 都是为了容器的调度和编排系统&#xff0c;但是rancher不仅能够调度&#xff0c;还能挂历k8s集群&#xff0c;自带监控&#xff08;普罗米修斯&#xff09;&#xff0c;你哪怕不知带k8s是什么&#xff0c;一样…

跟着pink老师前端入门教程-day09

二十二、定位 22.1 为什么需要定位 1. 某个元素可以自由的在一个盒子内移动位置&#xff0c;并且压住其他盒子 2. 当我们滚动窗口时&#xff0c;盒子是固定屏幕某个位置的 解决方法&#xff1a; 1. 浮动可以让多个块级盒子一行没有缝隙排列显示&#xff0c;经常用于横向排…

C#用DateTime.Now静态属性返回日期的星期信息

目录 一、使用的方法 1.Now属性 2.ToString方法 二、示例 使用DateTime结构的Now静态属性&#xff0c;可以方便地获取系统日期信息。调用时间对象的ToString方法&#xff0c;在该方法的参数中添加适当的格式化字符串&#xff0c;将返回日期的星期信息。 一、使用的方法 1…

C语言入门到精通之练习实例10:打印楼梯,同时在楼梯上方打印两个笑脸(附源码)

题目&#xff1a;打印楼梯&#xff0c;同时在楼梯上方打印两个笑脸。 程序分析&#xff1a;用 ASCII 1 来输出笑脸&#xff1b;用i控制行&#xff0c;j来控制列&#xff0c;j根据i的变化来控制输出黑方格的个数。 如果出现乱码情况请参考【C 练习实例7】的解决方法。 // Cr…

uniapp 在static/index.html中添加全局样式

前言 略 在static/index.html中添加全局样式 <style>div {background-color: #ccc;} </style>static/index.html源码&#xff1a; <!DOCTYPE html> <html lang"zh-CN"><head><meta charset"utf-8"><meta http-…

从零开始用Rust编写nginx,命令行参数的设计与解析及说明

wmproxy wmproxy已用Rust实现http/https代理, socks5代理, 反向代理, 静态文件服务器&#xff0c;四层TCP/UDP转发&#xff0c;七层负载均衡&#xff0c;内网穿透&#xff0c;后续将实现websocket代理等&#xff0c;会将实现过程分享出来&#xff0c;感兴趣的可以一起造个轮子 …

教育研究方法有哪些分类

教育研究方法的分类是多种多样的&#xff0c;可以从不同的角度进行划分。根据研究目的、研究范围、研究层次等&#xff0c;可以将教育研究方法分为不同的类型。 一、根据研究目的划分 基础性研究基础性研究也称为理论性研究&#xff0c;主要是为了探索和发现新的理论观点和原…

uniapp开发过程一些小坑

问题1、uniapp使用scroll-view的:scroll-into-view“lastChatData“跳到某个元素id时候&#xff0c;在app上不生效&#xff0c;小程序没问题 使用this.$nextTick或者 setTimeout(()>{that.lastChatData 元素id },500) 进行延后处理就可以了。 问题2&#xff1a;uniapp开…

运动刷步工具2.4。运动步数同步wx和支付宝

时隔一年&#xff1b;上次更新还是2022-11-26&#xff0c;陆续收到私信旧版已不能使用&#xff0c;2.4版本更新修复超时问题。后续有时间还会更新邮箱登录功能2023-11-15更新&#xff1a;修复错误超时问题测试不行的小伙伴&#xff0c;先看说明再使用&#xff01;&#xff01;&…