java Https post请求get请求 跳过验证

1- 最近跟别的部门对接几个接口 对方提供的是https 百度了好久 好多人用的方法都是过期的后面花了我一天半的时间去改跟百度 出来的结果跟大家分享一下

 2-先创建信任证书的管理器

import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

// 信任证书的管理器
public class MyX509TrustManager implements X509TrustManager {
   @Override
    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

    }

    @Override
    public X509Certificate[] getAcceptedIssuers() {
        return null;
    }
}

 3-创建忽略证书的跳过ssl  这个创建再post get请求页面上就行了


    //添加信任主机
    private static void trustAllHosts() {
        // 创建不验证证书链的信任管理器 这里使用的是x509证书
        TrustManager[] trustAllCerts = new TrustManager[]{new MyX509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        // 安装所有信任的信任管理器
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            //HttpsURLConnection通过SSLSocket来建立与HTTPS的安全连接,SSLSocket对象是由SSLSocketFactory生成的。
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //添加主机名验证程序类,设置不验证主机
    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };


    /**
     * map转url参数
     */
    public static String map2Url(Map<String, String> paramToMap) {
        if (null == paramToMap || paramToMap.isEmpty()) {
            return null;
        }
        StringBuffer url = new StringBuffer();
        boolean isfist = true;
        for (Map.Entry<String, String> entry : paramToMap.entrySet()) {
            if (isfist) {
                isfist = false;
            } else {
                url.append("&");
            }
            url.append(entry.getKey()).append("=");
            String value = entry.getValue();
            if (!StringUtils.isEmpty(value)) {
                url.append(value);
            }
        }
        return url.toString();
    }

4- https post请求 x-www-form-urlencoded  和form-data 提交的

 /**
     * 发送post 数据 请求 x-www-form-urlencoded  和form-data 提交的
     *
     * @param urls
     * @return
     */
    public static String sendPost(String urls, String param) {
        StringBuffer sb = new StringBuffer();
        DataOutputStream out = null;
        BufferedReader responseReader = null;

        InputStream in1 = null;
        try {
            // 跳过ssl 
            trustAllHosts();
            // 创建url资源
            URL url = new URL(urls);
            // 建立http连接
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            // 忽略证书
            conn.setHostnameVerifier(DO_NOT_VERIFY);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置允许输出
            conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置传递方式
            conn.setRequestMethod("POST");
            //System.out.println(conn.getRequestMethod());
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");

            // 转换为字节数组
//            byte[] data = (param).getBytes();
//            // 设置文件长度
//            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8" );
            // 开始连接请求
            conn.connect();
            out = new DataOutputStream(conn.getOutputStream());
            // 写入请求的字符串
            out.writeBytes(param);

            out.flush();
            out.close();

            //System.out.println(conn.getResponseCode());

            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                System.out.println("连接成功");
                // 请求返回的数据
                in1 = conn.getInputStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }
            } else {
                  System.out.println("连接成功");
                // 请求返回的数据
                in1 = conn.getErrorStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }

            }
        } catch (Exception e) {

        } finally {
            try {
                if (null != responseReader)
                    responseReader.close();
                if (null != in1)
                    in1.close();
            } catch (Exception e) {
            }
            try {
                out.close();
            } catch (Exception e) {
            }
        }

        return sb.toString();

    }

 3-测试发送

   Map<String, String> paramData = new HashMap<String, String>();
   paramData.put("client", clientId);
   paramData.put("secret", clientSecret);
   paramData.put("type", grantType);
   String s = HttpRequestUtil.sendPost(url, HttpRequestUtil.map2Url(paramData));

 

 5- https post 请求 json 格式发送数据

 /**
     * 发送post 数据
     *
     * @param urls
     * @return
     */
    public static String sendPost(String urls, String param,String token) {
        StringBuffer sb = new StringBuffer();
        //PrintWriter out = null;
         DataOutputStream out=null;
        BufferedReader responseReader = null;

        InputStream in1 = null;
        try {
             // 跳过ssl验证
            trustAllHosts();
            // 创建url资源
            URL url = new URL(urls);
            // 建立http连接
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            // 忽略证书
            conn.setHostnameVerifier(DO_NOT_VERIFY);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置允许输出
            conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置传递方式
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            // 根据对方提供的接口要不要携带token  不要的话直接传null 就行了
            if (token !=null) {
                conn.setRequestProperty("Authorization", token);
            }
            // 设置传递方式
            conn.setRequestMethod("POST");
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 开始连接请求
            conn.connect();
            //获取服务端发送的信息:conn.getOutputStream()
            // POST请求
            out = new DataOutputStream(conn.getOutputStream());
            out.writeChars(param);

            out.flush();
            out.close();
            System.out.println(conn.getResponseCode());
            System.out.println(conn.getInputStream());
            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {

                System.out.println("连接成功");
                // 请求返回的数据
                in1 = conn.getInputStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }

            } else {
                  System.out.println("连接成功");
                // 请求返回的数据
                in1 = conn.getErrorStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }

            }
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            try {
                if (null != responseReader)
                    responseReader.close();
                if (null != in1)
                    in1.close();
            } catch (Exception e) {
            }
            try {
                out.close();
            } catch (Exception e) {
            }
        }

        return sb.toString();

    }

6- 对象转成json格式传递

// 对象转成json 格式的字符串 
String data = JSON.toJSONString(ooo);
// 发送json格式的请求
String reqData = httpstow.sendPost(url,data,toke );

 7- 发送get请求  其实get请求跟上面的是一样的 我这里就直接路径拼接参数就行了

  /**
     * 发送get 数据
     *
     * @param urls
     * @return
     */
    public static String sendGet(String urls,String token) {
        StringBuffer sb = new StringBuffer();
        DataOutputStream out = null;
        BufferedReader responseReader = null;

        InputStream in1 = null;
        try {
            // 跳过ssl验证
            trustAllHosts();
            // 创建url资源
            URL url = new URL(urls);
            // 建立http连接
            HttpsURLConnection conn= (HttpsURLConnection) url.openConnection();
            // 忽略证书
            conn.setHostnameVerifier(DO_NOT_VERIFY);
            // 设置不用缓存
           conn.setUseCaches(false);
            // 设置允许输出
            conn.setDoOutput(true);
            // 设置允许输入
           conn.setDoInput(true);
            // 设置传递方式
           conn.setRequestMethod("GET");
            //System.out.println(conn.getRequestMethod());
            // 设置维持长连接
           conn.setRequestProperty("connection", "keep-alive");
            // 设置文件字符集:
          //  conn.setRequestProperty("Charset", "UTF-8");

            // 转换为字节数组
//            byte[] data = (param).getBytes();
//            // 设置文件长度
//            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            if (token !=null) {
                // 设置文件类型:
                conn.setRequestProperty("Authorization", token);
            }
            // 开始连接请求
            conn.connect();


           // out = new DataOutputStream(conn.getOutputStream());
            // 写入请求的字符串
           // out.writeBytes(param);

            //out.flush();
            //out.close();

            //System.out.println(conn.getResponseCode());

            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                System.out.println("连接成功");
                // 请求返回的数据
                in1 = conn.getInputStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }
            } else {
                System.out.println("连接成功");
                // 请求返回的数据
                in1 = conn.getErrorStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while ((readLine = responseReader.readLine()) != null) {
                    sb.append(readLine).append("\n");
                }

            }
        } catch (Exception e) {

        } finally {
            try {
                if (null != responseReader)
                    responseReader.close();
                if (null != in1)
                    in1.close();
            } catch (Exception e) {
            }
            try {
                out.close();
            } catch (Exception e) {
            }
        }

        return sb.toString();

    }

8-测试发送数据

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java中发送POST请求跳过证书验证,可以使用HttpsURLConnection类的一些方法来实现。以下是一种示例代码,其中使用了TrustManager和HostnameVerifier来跳过证书验证: ```java import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.security.cert.X509Certificate; public class HttpsPost { public static void main(String[] args) throws Exception { String url = "https://example.com/api"; String data = "param1=value1&param2=value2"; // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = (hostname, session) -> true; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); // Send POST request URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.getOutputStream().write(data.getBytes("UTF-8")); // Get response BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // Print response System.out.println(response.toString()); } } ``` 在上面的代码中,我们创建了一个TrustManager,该TrustManager不验证证书链。然后,我们使用该TrustManager创建了一个SSLContext,并将其设置为默认的SSLSocketFactory。接下来,我们创建了一个HostnameVerifier,该Verifier接受所有主机名,并将其设置为默认的HostnameVerifier。最后,我们使用HttpsURLConnection类来发送POST请求,该请求跳过证书验证

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值