二、java发送https的各类请求

导航

一、java发送http的各类请求

二、java发送https的各类请求 

  java开发中需要调用其他服务的对外提供的https请求,上一篇写的是调用http,处理方式不太一样,可以参考如下代码:

注:调用的主类比较简单就不写了。

pom.xml

复制代码
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>
 
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
复制代码
HttpsUtil.class类
package cn.cas.xjipc.yjsapplication.unit;


import org.apache.commons.httpclient.util.HttpURLConnection;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.*;

@Component
public class HttpsUtil {

    private static class TrustAnyTrustManager implements X509TrustManager {

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

        public void checkServerTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[]{};
        }
    }

    private static class TrustAnyHostnameVerifier implements HostnameVerifier {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }

    /**
     * post方式请求服务器(https协议)
     *
     * @param url     请求地址
     * @param content 参数
     * @param charset 编码
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     */
    public String post(String url, String content, String charset)
            throws NoSuchAlgorithmException, KeyManagementException,
            IOException {
        String result = "";
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[]{new TrustAnyTrustManager()},
                new java.security.SecureRandom());

        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.setDoOutput(true);
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        out.write(content.getBytes(charset));
        // 刷新、关闭
        out.flush();
        out.close();
        InputStream is = conn.getInputStream();
        if (is != null) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();
            byte[] array = outStream.toByteArray();
            result = new String(array, "utf-8");
            return result;
        }
        return null;
    }


    /**
     * put方式请求服务器(https协议)
     *
     * @param url     请求地址
     * @param content 参数
     * @param token   编码
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     */
    public String put(String url, String content, String token)
            throws NoSuchAlgorithmException, KeyManagementException,
            IOException {
        String result = "";
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[]{new TrustAnyTrustManager()},
                new java.security.SecureRandom());

        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setRequestMethod("PUT");
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        //conn.setRequestProperty("Authorization", "xxxxx" + token);
        conn.connect();
        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        //out.write(content.getBytes("UTF8"));
        // 刷新、关闭
        out.flush();
        out.close();
        InputStream is = conn.getInputStream();
        if (is != null) {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }
            is.close();

            byte[] array = outStream.toByteArray();
            result = new String(array, "utf-8");
            return result;
        }
        return null;
    }

    /**
     * get方式请求服务器(https协议)
     *
     * @param url     请求地址
     * @param content 参数
     * @param token   编码
     * @return
     * @throws NoSuchAlgorithmException
     * @throws KeyManagementException
     * @throws IOException
     */
    public String get(String url, String content, String token)
            throws NoSuchAlgorithmException, KeyManagementException,
            IOException {
        String result = "";
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[]{new TrustAnyTrustManager()},
                new java.security.SecureRandom());

        URL httpUrl = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) httpUrl.openConnection();
        conn.setRequestMethod("GET");
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.setDoOutput(true);

        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        //conn.setRequestProperty("Authorization", "xxxxxx" + token);
        conn.connect();

//get方法与post方法除了conn.setRequestMethod("GET")这句不一样外,关于DataOutputStream out的几行一定要删除,否则就会报405的错误 InputStream is
= conn.getInputStream(); if (is != null) { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); byte[] array = outStream.toByteArray(); result = new String(array, "utf-8"); return result; } return null; } }

 

 

资源丰富的的网盘资源:网盘资源大全! 推荐一个适合零基础学习SQL的网站:不用安装数据库,在线轻松学习SQL!
posted @ 2021-07-19 17:19  万笑佛  阅读(4859)  评论(0编辑  收藏  举报