封装 HttpClient 的Get、Post、Put、Delete四种请求(个人笔记)

  • pom引入依赖
<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.5</version>
</dependency>
  • 工具类HttpClientUtil
package com.keda.mediaschedule.common.utils;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
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.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @date: 2021/8/5 14:07
 * @author: wangjw
 * @Description: http请求工具类
 */
public class HttpClientUtil {

    /**
     * Get请求
     * @param url http地址
     * @param paraMap 请求参数
     * @param headerMap 定义的header
     * @return
     */
   public static String sendGet(String url,Map<String,Object> paraMap, Map<String, String> headerMap) throws Exception{
       String content = "";
       CloseableHttpClient httpClient = null;
       CloseableHttpResponse httpResponse = null;
       try {
           // 声明URIBuilder
           URIBuilder uriBuilder = new URIBuilder(url);
           // 设置参数
           if (null != paraMap && paraMap.size() > 0) {
               for (Map.Entry<String, Object> entry : paraMap.entrySet()) {
                   uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
               }
           }
           HttpGet httpGet = new HttpGet(uriBuilder.build());
           httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
           //自定义的header内容
           if (null != headerMap && headerMap.size() > 0) {
               headerMap.forEach((key,value)->{
                   httpGet.addHeader(key, value);
               });
           }
           httpClient = HttpClients.createDefault();
           // 执行请求并获取返回
           httpResponse = httpClient.execute(httpGet);
           HttpEntity entity = httpResponse.getEntity();
           content = EntityUtils.toString(entity);
       } finally {
           if (null != httpResponse){
               httpResponse.close();
           }
           if (null != httpClient){
               httpClient.close();
           }
       }
       return content;
   }

    /**
     * Post请求
     * @param url http地址
     * @param jsonStr 请求参数json字符串格式
     * @param headerMap 定义的header
     * @return
     */
    public static String sendPost(String url, String jsonStr, Map<String, String> headerMap) throws Exception{
        System.out.println(url);
        String content = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(6000).build();
        httpPost.setConfig(requestConfig);
        //默认header
        httpPost.setHeader("Content-type", "application/json;charset=utf-8");
        //自定义的header内容
        if (null != headerMap && headerMap.size() > 0) {
            headerMap.forEach((key,value)->{
                httpPost.addHeader(key, value);
            });
        }
        CloseableHttpResponse httpResponse = null;
        try {
            httpPost.setEntity(new StringEntity(jsonStr, "utf-8"));
                httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity,"UTF-8");
        } finally{
            if (null != httpResponse) {
                httpResponse.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }
        return content;
    }


    /**
     * Put请求
     * @param url http地址
     * @param jsonStr 请求参数json字符串格式
     * @param headerMap 定义的header
     * @return
     */
    public static String sendPut(String url, String jsonStr, Map<String, String> headerMap) throws Exception{
        String content = "";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPut httpPut = new HttpPut(url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(6000).build();
        httpPut.setConfig(requestConfig);
        httpPut.setHeader("Content-type", "application/json;charset=utf-8");
        //自定义的header内容
        if (null != headerMap && headerMap.size() > 0) {
            headerMap.forEach((key,value)->{
                httpPut.addHeader(key, value);
            });
        }
        CloseableHttpResponse httpResponse = null;
        try {
            httpPut.setEntity(new StringEntity(jsonStr,"utf-8"));
            httpResponse = httpClient.execute(httpPut);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity,"UTF-8");
        } finally {
            if (null != httpResponse) {
                httpResponse.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }
        return content;
    }

    /**
     * Delete请求
     * @param url http地址
     * @param headerMap 定义的header
     * @return
     */
    public static String sendDelete(String url, Map<String,String> headerMap) throws Exception{
        String content = null;
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpDelete httpdelete = new HttpDelete(url);
        httpdelete.setHeader("Content-type", "application/json;charset=utf-8");
        // 自定义的header内容
        if (null != headerMap && headerMap.size() > 0) {
            headerMap.forEach((key,value)-> httpdelete.addHeader(key, value));
        }
        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpdelete);
            HttpEntity entity = httpResponse.getEntity();
            content = EntityUtils.toString(entity, "UTF-8");
        }  finally {
            if (null != httpResponse) {
                httpResponse.close();
            }
            if (null != httpClient) {
                httpClient.close();
            }
        }
        return content;
    }
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值