总结:封装Java后端开发中常用的HttpUtil工具类,以及如何利用HttpURLConnection访问需要账号密码的URL

一·写这篇博客的背景:

(1)Java程序后端开发中,经常会需要发起http请求从某个接口获取对应的报文信息

(2)本文只利用JDK8原生API(HttpURLConnection),封装一个发起http请求的工具类

(3)本工具类暂时只有get、post两种类型请求

(4)本工具类封装的请求方法中包括各种http请求细节设置,例如:如何设置请求头、post请求如何将参数写入进去、如何设置访问URL所需的账号密码、如何获取异常响应流等等

(5)HttpURLConnection类仅默认信任CA机构签发的有效证书,其他自签证书都是不信任的,也就有可能导致该工具类不会发起https请求

这句话如何理解?
(1)本文章封装的工具类发送可以发送所有http协议请求;
(2)对于https协议请求,只有当服务器是使用正规CA机构签发的证书时,该工具类才能正确发送请求获取响应结果。
比如利用该工具类访问“https://www.baidu.com”,就可以正常接收响应结果。
(3)如果有的公司服务器是使用自签证书,那该工具类是不会发送任何https请求的

什么是证书?
(1)服务器申请或者生成证书时,证书里面会包含公钥、私钥。
(2)客户端第一次发起请求时(此时未加密),服务器就会将只包含公钥的证书发给客户端,从而进行后续的加密通信请求
(3)详情可以去参考https协议

二·完整工具类封装代码:

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;


public class HttpUtil {

    private static int timeOut = 60000; // http超时时间


    /**
     * get请求,不能访问加密URL
     *
     * @param requestURL 请求地址
     * @return 响应结果
     * @throws IOException
     */
    public static String doGet(String requestURL) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("GET");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();


            /*
             * 开始发起get类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }


    /**
     * get请求,不能访问加密URL
     *
     * @param requestURL         请求地址
     * @param requestPropertyMap url中的请求头键值对
     * @return 响应结果
     * @throws IOException
     */
    public static String doGet(String requestURL, Map<String, String> requestPropertyMap) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("GET");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");

            //自动遍历添加请求属性信息(例如:请求头属性等等)
            if (!requestPropertyMap.isEmpty()) {
                for (String key : requestPropertyMap.keySet()) {
                    conn.setRequestProperty(key, requestPropertyMap.get(key));
                }
            }

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             * 开始发起get类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }

    /**
     * get请求,可以访问加密URL
     *
     * @param requestURL         请求地址
     * @param username           url账号
     * @param password           url密码
     * @return 响应结果
     * @throws IOException
     */
    public static String doGet(String requestURL, String username, String password) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时Map
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("GET");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");

            //设置安全验证的账号密码
            Base64.Encoder encoder = Base64.getEncoder();
            //对字符串进行编码加密:base64
            String encode = encoder.encodeToString((username + ":" + password).getBytes());
            //为URLConnection 设置“授权”要求属性
            conn.setRequestProperty("Authorization", "Basic " + encode);

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             * 开始发起get类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }


    /**
     * get请求,可以访问加密URL
     *
     * @param requestURL         请求地址
     * @param username           url账号
     * @param password           url密码
     * @param requestPropertyMap url中的请求头键值对
     * @return 响应结果
     * @throws IOException
     */
    public static String doGet(String requestURL, Map<String, String> requestPropertyMap, String username, String password) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时Map
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("GET");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");

            //自动遍历添加请求属性信息(例如:请求头属性等等)
            if (!requestPropertyMap.isEmpty()) {
                for (String key : requestPropertyMap.keySet()) {
                    conn.setRequestProperty(key, requestPropertyMap.get(key));
                }
            }

            //设置安全验证的账号密码
            Base64.Encoder encoder = Base64.getEncoder();
            //对字符串进行编码加密:base64
            String encode = encoder.encodeToString((username + ":" + password).getBytes());
            //为URLConnection 设置“授权”要求属性
            conn.setRequestProperty("Authorization", "Basic " + encode);

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             * 开始发起get类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }


    /**
     * post请求,不能访问加密URL
     *
     * @param requestURL 请求地址
     * @param body       请求体
     * @return 响应结果
     * @throws IOException
     */
    public static String doPost(String requestURL, String body) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        OutputStream outputStream = null;
        BufferedWriter writer = null;
        try {
            //创建链接地址
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置是否允许从httpUrlConnection读取数据,默认是true
            conn.setDoInput(true);
            //设置是否向httpUrlConnection输出参数,因为这个是post请求,所以必须开启
            conn.setDoOutput(true);
            //设置连接超时
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("POST");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");
            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的请求头配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             *  往post连接里面写入必要的请求体-参数
             */
            //获取conn的输出流
            outputStream = conn.getOutputStream();
            //将字节流转换为字符流
            writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            //往连接中写入参数,body可以是name=lmf&age=23键值对拼接形式,也可以是json字符串形式
            writer.write(body);
            //必须刷新流空间的数据
            writer.flush();

            /*
             * 开始发起post类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            //最终响应内容字符串
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }


    /**
     * post请求,可以访问加密URL
     *
     * @param requestURL 请求地址
     * @param body       请求体
     * @param username   url账号
     * @param password   url密码
     * @return 响应结果
     * @throws IOException
     */
    public static String doPost(String requestURL, String body, String username, String password) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        OutputStream outputStream = null;
        BufferedWriter writer = null;
        try {
            //创建链接地址
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置是否允许从httpUrlConnection读取数据,默认是true
            conn.setDoInput(true);
            //设置是否向httpUrlConnection输出参数,因为这个是post请求,所以必须开启
            conn.setDoOutput(true);
            //设置连接超时
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("POST");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");
            //设置安全验证的账号密码
            Base64.Encoder encoder = Base64.getEncoder();
            //对字符串进行编码加密:base64
            String encode = encoder.encodeToString((username + ":" + password).getBytes());
            //为URLConnection 设置“授权”要求属性
            conn.setRequestProperty("Authorization", "Basic " + encode);

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的请求头配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             *  往post连接里面写入必要的请求体-参数
             */
            //获取conn的输出流
            outputStream = conn.getOutputStream();
            //将字节流转换为字符流
            writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            //往连接中写入参数,body可以是name=lmf&age=23键值对拼接形式,也可以是json字符串形式
            writer.write(body);
            //必须刷新流空间的数据
            writer.flush();

            /*
             * 开始发起post类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            //最终响应内容字符串
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }
}

三·GET请求封装代码:

private static int timeOut = 60000; // http超时时间


    /**
     * get请求,不能访问加密URL
     *
     * @param requestURL 请求地址
     * @return 响应结果
     * @throws IOException
     */
    public static String doGet(String requestURL) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("GET");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();


            /*
             * 开始发起get类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }


    /**
     * get请求,不能访问加密URL
     *
     * @param requestURL         请求地址
     * @param requestPropertyMap url中的请求头键值对
     * @return 响应结果
     * @throws IOException
     */
    public static String doGet(String requestURL, Map<String, String> requestPropertyMap) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("GET");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");

            //自动遍历添加请求属性信息(例如:请求头属性等等)
            if (!requestPropertyMap.isEmpty()) {
                for (String key : requestPropertyMap.keySet()) {
                    conn.setRequestProperty(key, requestPropertyMap.get(key));
                }
            }

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             * 开始发起get类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }

    /**
     * get请求,可以访问加密URL
     *
     * @param requestURL         请求地址
     * @param username           url账号
     * @param password           url密码
     * @return 响应结果
     * @throws IOException
     */
    public static String doGet(String requestURL, String username, String password) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时Map
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("GET");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");

            //设置安全验证的账号密码
            Base64.Encoder encoder = Base64.getEncoder();
            //对字符串进行编码加密:base64
            String encode = encoder.encodeToString((username + ":" + password).getBytes());
            //为URLConnection 设置“授权”要求属性
            conn.setRequestProperty("Authorization", "Basic " + encode);

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             * 开始发起get类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }


    /**
     * get请求,可以访问加密URL
     *
     * @param requestURL         请求地址
     * @param username           url账号
     * @param password           url密码
     * @param requestPropertyMap url中的请求头键值对
     * @return 响应结果
     * @throws IOException
     */
    public static String doGet(String requestURL, Map<String, String> requestPropertyMap, String username, String password) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        try {
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置连接超时Map
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("GET");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");

            //自动遍历添加请求属性信息(例如:请求头属性等等)
            if (!requestPropertyMap.isEmpty()) {
                for (String key : requestPropertyMap.keySet()) {
                    conn.setRequestProperty(key, requestPropertyMap.get(key));
                }
            }

            //设置安全验证的账号密码
            Base64.Encoder encoder = Base64.getEncoder();
            //对字符串进行编码加密:base64
            String encode = encoder.encodeToString((username + ":" + password).getBytes());
            //为URLConnection 设置“授权”要求属性
            conn.setRequestProperty("Authorization", "Basic " + encode);

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             * 开始发起get类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }

四·POST请求封装代码:

private static int timeOut = 60000; // http超时时间

    /**
     * post请求,不能访问加密URL
     *
     * @param requestURL 请求地址
     * @param body       请求体
     * @return 响应结果
     * @throws IOException
     */
    public static String doPost(String requestURL, String body) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        OutputStream outputStream = null;
        BufferedWriter writer = null;
        try {
            //创建链接地址
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置是否允许从httpUrlConnection读取数据,默认是true
            conn.setDoInput(true);
            //设置是否向httpUrlConnection输出参数,因为这个是post请求,所以必须开启
            conn.setDoOutput(true);
            //设置连接超时
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("POST");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");
            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的请求头配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             *  往post连接里面写入必要的请求体-参数
             */
            //获取conn的输出流
            outputStream = conn.getOutputStream();
            //将字节流转换为字符流
            writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            //往连接中写入参数,body可以是name=lmf&age=23键值对拼接形式,也可以是json字符串形式
            writer.write(body);
            //必须刷新流空间的数据
            writer.flush();

            /*
             * 开始发起post类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            //最终响应内容字符串
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }


    /**
     * post请求,可以访问加密URL
     *
     * @param requestURL 请求地址
     * @param body       请求体
     * @param username   url账号
     * @param password   url密码
     * @return 响应结果
     * @throws IOException
     */
    public static String doPost(String requestURL, String body, String username, String password) throws IOException {
        BufferedReader inReader = null;
        InputStream in = null;
        String responseBody = "";
        OutputStream outputStream = null;
        BufferedWriter writer = null;
        try {
            //创建链接地址
            URL url = new URL(requestURL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //设置是否允许从httpUrlConnection读取数据,默认是true
            conn.setDoInput(true);
            //设置是否向httpUrlConnection输出参数,因为这个是post请求,所以必须开启
            conn.setDoOutput(true);
            //设置连接超时
            conn.setConnectTimeout(timeOut);
            //设置读取超时
            conn.setReadTimeout(timeOut);
            //设置请求方法
            conn.setRequestMethod("POST");
            //设置请求头信息
            conn.setRequestProperty("Content-Type", "application/json");
            //设置安全验证的账号密码
            Base64.Encoder encoder = Base64.getEncoder();
            //对字符串进行编码加密:base64
            String encode = encoder.encodeToString((username + ":" + password).getBytes());
            //为URLConnection 设置“授权”要求属性
            conn.setRequestProperty("Authorization", "Basic " + encode);

            /*
             * connect()会根据HttpURLConnection对象的配置值生成HTTP头部信息,且建立tcp连接,但是没有发送http请求
             * 所有的请求头配置信息,都必须在connect()方法之前添加,后面的添加不进去。
             */
            conn.connect();

            /*
             *  往post连接里面写入必要的请求体-参数
             */
            //获取conn的输出流
            outputStream = conn.getOutputStream();
            //将字节流转换为字符流
            writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
            //往连接中写入参数,body可以是name=lmf&age=23键值对拼接形式,也可以是json字符串形式
            writer.write(body);
            //必须刷新流空间的数据
            writer.flush();

            /*
             * 开始发起post类型http请求,获取响应数据
             */
            //实际发送url的http请求
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                //获取正常响应流
                in = conn.getInputStream();
            } else {
                //获取异常响应流
                in = conn.getErrorStream();
            }
            //读取响应内容
            inReader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            StringBuilder sb = new StringBuilder();
            int len;
            char[] tmp = new char[256];
            while ((len = inReader.read(tmp)) > 0) {
                sb.append(tmp, 0, len);
            }
            //最终响应内容字符串
            responseBody = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
            if (inReader != null) {
                inReader.close();
            }
            if (in != null) {
                in.close();
            }
        }
        return responseBody;
    }

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ideal-cs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值