Http请求封装类 get, post, put, delete

话不多说直接上代码 !

import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.*;
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.util.EntityUtils;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Map;

/**
 * Http请求封装类
 * @author 李扬
 */
public class HttpUtils {

    /**
     * 向指定URL发送GET请求
     *
     * @param url      发送请求的URL
     * @param param    请求参数(可为空)
     * @return result  响应结果
     */
    public static String sendGet(String url, Map<String, String> param) {
        String urlStr = url;
        // 参数处理
        if (!ObjectUtils.isEmpty(param)) {
            StringBuilder paramStr = new StringBuilder();
            for (String key : param.keySet()) {
                paramStr.append("&").append(key).append("=").append(param.get(key));
            }
            String paramString = String.valueOf(paramStr);
            if (!url.contains("?")) paramString = paramString.replaceFirst("&", "?");
            urlStr = url + paramString;
        }
        // 获取连接
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse;
        String resultString = null;
        HttpGet httpGet = new HttpGet(urlStr);
        // 设置header信息
        httpGet.setHeader("Accept", "*/*");
        httpGet.setHeader("Accept-Encoding", "gzip, deflate");
        httpGet.setHeader("Cache-Control", "no-cache");
        httpGet.setHeader("Connection", "keep-alive");
        httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
        try {
            httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            resultString = EntityUtils.toString(entity, "UTF-8");
            try {
                httpResponse.close();
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultString;
    }

    /**
     * 向指定URL发送POST请求
     *
     * @param url      发送请求的URL
     * @param param    请求参数(不可为空)
     * @return result  响应结果
     */
    public static String sendPost(String url, Map param){
        // 返回body
        String body = null;
        // 获取连接客户端工具
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse=null;
        // 创建一个HttpPost请求
        HttpPost post = new HttpPost(url);
        // 设置header信息
        post.setHeader("Accept", "*/*");
        post.setHeader("Accept-Encoding", "gzip, deflate");
        post.setHeader("Cache-Control", "no-cache");
        post.setHeader("Connection", "keep-alive");
        post.setHeader("Content-Type", "application/json;charset=UTF-8");

        // 设置参数
        if (param != null) {
            try {
                StringEntity entity1=new StringEntity(JSON.toJSONString(param),"UTF-8");
                entity1.setContentEncoding("UTF-8");
                entity1.setContentType("application/json");
                post.setEntity(entity1);
                // 执行post请求操作,并拿到结果
                httpResponse = httpClient.execute(post);
                // 获取结果实体
                HttpEntity entity = httpResponse.getEntity();
                if (entity != null) {
                    // 按指定编码转换结果实体为String类型
                    body = EntityUtils.toString(entity, "UTF-8");
                }
                try {
                    httpResponse.close();
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return body;
    }

    /**
     * 向指定URL发送PUT请求
     *
     * @param url      发送请求的URL
     * @param param    请求参数(不可为空)
     * @return result  响应结果
     */
    public static String sendPut(String url, Map param) {
        String encode = "utf-8";
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(url);
        // 设置header信息
        httpput.setHeader("Accept", "*/*");
        httpput.setHeader("Accept-Encoding", "gzip, deflate");
        httpput.setHeader("Cache-Control", "no-cache");
        httpput.setHeader("Connection", "keep-alive");
        httpput.setHeader("Content-Type", "application/json;charset=UTF-8");
        // 组织请求参数
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(param), encode);
        httpput.setEntity(stringEntity);
        String content = null;
        CloseableHttpResponse httpResponse = null;
        try {
            // 响应信息
            httpResponse = closeableHttpClient.execute(httpput);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            closeableHttpClient.close(); // 关闭连接、释放资源
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 向指定URL发送delete请求
     *
     * @param url      发送请求的URL
     * @param param    请求参数(可为空)
     * @return result  响应结果
     */
    public static String sendDelete(String url, Map<String, String> param) {
        String urlStr = url;
        // 参数处理
        if (!ObjectUtils.isEmpty(param)) {
            StringBuilder paramStr = new StringBuilder();
            for (String key : param.keySet()) {
                paramStr.append("&").append(key).append("=").append(param.get(key));
            }
            String paramString = String.valueOf(paramStr);
            if (!url.contains("?")) paramString = paramString.replaceFirst("&", "?");
            urlStr = url + paramString;
        }
        String encode = "utf-8";
        String content = null;
        CloseableHttpClient closeableHttpClient = HttpClientBuilder.create().build();
        HttpDelete httpdelete = new HttpDelete(urlStr);
        // 设置header信息
        httpdelete.setHeader("Accept", "*/*");
        httpdelete.setHeader("Accept-Encoding", "gzip, deflate");
        httpdelete.setHeader("Cache-Control", "no-cache");
        httpdelete.setHeader("Connection", "keep-alive");
        httpdelete.setHeader("Content-Type", "application/json;charset=UTF-8");
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = closeableHttpClient.execute(httpdelete);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, encode);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpResponse.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            closeableHttpClient.close(); // 关闭连接、释放资源
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

佛係老李

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

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

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

打赏作者

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

抵扣说明:

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

余额充值