HttpUrlConnection发送GET和POST请求的工具类

使用HttpUrlConnection发送GET和POST请求的工具类:

废话不多说直接上代码:

package com.zoho.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Author: WangChenYang
 * @Date: 2021/7/27 10:37
 */
public class HttpUrlConnectionUtils {


    /**
     * 普通GET
     *
     * @param requestUrl
     * @return
     */
    public static String get(String requestUrl) {
        return get(requestUrl, new HashMap<String, String>(), new HashMap<String, String>());
    }

    /**
     * 带参Get
     *
     * @param requestUrl
     * @param params
     * @return
     */
    public static String get(String requestUrl, Map<String, String> params) {
        return get(requestUrl, params, new HashMap<String, String>());
    }

    /**
     * GET请求(带参,带headers)
     *
     * @param requestUrl
     * @param params
     * @param headers
     * @return
     */
    public static String get(String requestUrl, Map<String, String> params, Map<String, String> headers) {
        if (requestUrl == null || "".equals(requestUrl)) {
            throw new RuntimeException("URL不正确!");
        }
        String finalUrl = requestUrl;
        if (!params.isEmpty()) {
            String urlParam = "";
            if (!params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    String s = key + "=" + value + "&";
                    urlParam += s;
                }
            }
            finalUrl = requestUrl + "?" + urlParam.substring(0, urlParam.length() - 1);
        }
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;
        try {
            /** 创建远程url连接对象 */
            URL url = new URL(finalUrl);
            /** 通过远程url对象打开一个连接,强制转换为HttpUrlConnection类型 */
            connection = (HttpURLConnection) url.openConnection();
            /** 设置连接方式:GET */
            connection.setRequestMethod("GET");
            /** 设置连接主机服务器超时时间:15000毫秒 */
            connection.setConnectTimeout(15000);
            /** 设置读取远程返回的数据时间:60000毫秒 */
            connection.setReadTimeout(60000);
            /** 设置通用的请求属性 */
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            if (!headers.isEmpty()) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    connection.setRequestProperty(key, value);
                }
            }
            /** 发送GET方式请求,使用connet方法建立和远程资源之间的实际连接即可 */
            connection.connect();
            /*-------------------------->*/
            /** 获取所有相应头字段 */
            Map<String, List<String>> map = connection.getHeaderFields();
            /** 遍历响应头字段 */
            for (String key : map.keySet()) {
                System.out.println(key + "---------->" + map.get(key));
            }
            /* <-------------------------- */
            /** 请求成功:返回码为200 */
            if (connection.getResponseCode() == 200) {
                /** 通过connection连接,获取输入流 */
                is = connection.getInputStream();
                /** 封装输入流is,并指定字符集 */
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                /** 存放数据 */
                StringBuffer sbf = new StringBuffer();
                String line = null;
                while ((line = br.readLine()) != null) {
                    sbf.append(line);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            /** 关闭资源 */
            try {
                if (null != br) {
                    br.close();
                }
                if (null != is) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            /** 关闭远程连接 */
            // 断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            // 固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些
            connection.disconnect();
            System.out.println("--------->>> GET request end <<<----------");
        }
        return result;
    }

    /**
     * 普通post请求
     *
     * @param requestUrl
     * @return
     */
    public static String post(String requestUrl) {
        return post(requestUrl, null, null);
    }

    /**
     * post不带Heard
     *
     * @param requestUrl
     * @param param
     * @return
     */
    public static String post(String requestUrl, String param) {
        return post(requestUrl, param, new HashMap<String, String>());
    }

    /**
     * post不带Heard
     *
     * @param requestUrl
     * @param param
     * @return
     */
    public static String post(String requestUrl, Map<String, String> param) {
        String params = "";
        if (!param.isEmpty()) {
            Set<Map.Entry<String, String>> entries = param.entrySet();
            for (Map.Entry<String, String> entry : entries) {
                String key = entry.getKey();
                String value = entry.getValue();
                String s = key + "=" + value + "&";
                params += s;
            }
        }
        return post(requestUrl, params.substring(0, params.length() - 1));
    }


    /**
     * POST请求(带heard)
     *
     * @param requestUrl 请求地址
     * @param param      请求数据
     * @return
     */
    public static String post(String requestUrl, String param, Map<String, String> headers) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;

        try {
            /** 创建远程url连接对象 */
            URL url = new URL(requestUrl);
            /** 通过远程url对象打开一个连接,强制转换为HttpUrlConnection类型 */
            connection = (HttpURLConnection) url.openConnection();
            /** 设置连接方式:POST */
            connection.setRequestMethod("POST");
            /** 设置连接主机服务器超时时间:15000毫秒 */
            connection.setConnectTimeout(15000);
            /** 设置读取远程返回的数据时间:60000毫秒 */
            connection.setReadTimeout(60000);
            /** 设置是否向httpUrlConnection输出,设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个 */
            // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
            connection.setDoOutput(true);
            // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
            connection.setDoInput(true);
            /** 设置通用的请求属性 */
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            /*传过来的heards*/
            if (!headers.isEmpty()) {
                Set<Map.Entry<String, String>> entries = headers.entrySet();
                for (Map.Entry<String, String> entry : entries) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    connection.setRequestProperty(key, value);
                }
            }
            /** 通过连接对象获取一个输出流 */
            os = connection.getOutputStream();
            /** 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的 */
            // 若使用os.print(param);则需要释放缓存:os.flush();即使用字符流输出需要释放缓存,字节流则不需要
            if (param != null && param.length() > 0) {
                os.write(param.getBytes());
            }
            /** 请求成功:返回码为200 */
            if (connection.getResponseCode() == 200) {
                /** 通过连接对象获取一个输入流,向远程读取 */
                is = connection.getInputStream();
                /** 封装输入流is,并指定字符集 */
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                /** 存放数据 */
                StringBuffer sbf = new StringBuffer();
                String line = null;
                while ((line = br.readLine()) != null) {
                    sbf.append(line);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            /** 关闭资源 */
            try {
                if (null != br) {
                    br.close();
                }
                if (null != is) {
                    is.close();
                }
                if (null != os) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            /** 关闭远程连接 */
            // 断开连接,最好写上,disconnect是在底层tcp socket链接空闲时才切断。如果正在被其他线程使用就不切断。
            // 固定多线程的话,如果不disconnect,链接会增多,直到收发不出信息。写上disconnect后正常一些
            connection.disconnect();
            System.out.println("--------->>> POST request end <<<----------");
        }
        return result;
    }
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值