apache httpClient工具类

前言

记录java工具类,该工具类能够调用别人的接口,支持POST和GET请求,可用在maven或springboot项目

准备

导入依赖

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.2</version>
</dependency>

具体实现

import org.apache.http.HttpEntity;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
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 java.io.IOException;
import java.net.URI;
import java.util.Map;

public class HttpClientUtil {
// 调用POST请求
    public static <T> String sendPost(String url,String requestBody) throws Exception {
        // 创建post请求
        HttpPost post = new HttpPost(url);
        // 设置头
        post.setHeader("Content-Type", "application/json");
        // 设置请求设置
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(180000).setConnectionRequestTimeout(180000)
                .setSocketTimeout(180000).setRedirectsEnabled(true).build();
        post.setConfig(requestConfig);

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        CloseableHttpClient httpClient = HttpClientBuilder.create()
                .setDefaultCredentialsProvider((CredentialsProvider)basicCredentialsProvider)
                .build();
        // 设置发送体
        post.setEntity((HttpEntity)new StringEntity(requestBody, ContentType.create("application/json", "utf-8")));
        try  {
//            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = httpClient.execute(post);
            if (response != null && response.getStatusLine().getStatusCode() ==200) {
                String str = EntityUtils.toString(response.getEntity());
                System.out.println("请求结果:"+str);
                return str;
            }
            // 请求结果
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("调用失败:"+result);
            return "调用失败:"+result;
        } catch (Exception e) {
            e.printStackTrace();
            return "调用异常";
        } finally {
            if (httpClient!=null) {
                try {
                    httpClient.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

// 调用Get请求
    public static <T> String sendGet(String url, Map<String,String> param) throws Exception {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 返回结果
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            //创建uri
            URIBuilder builder=new URIBuilder(url);
            if (param != null) {
                for(String key : param.keySet()){
                    builder.addParameter(key,param.get(key));
                }
            }
            URI uri =builder.build();
            // 创建http get请求
            HttpGet httpGet=new HttpGet(uri);
            // 执行请求
            response =httpClient.execute(httpGet);
            // 判断返回状态是否返回200
            if (response.getStatusLine().getStatusCode() == 200) {
                resultString =EntityUtils.toString(response.getEntity(),"UTF-8");
            }
        } catch (Exception e) {
            System.out.println("系统错误:"+e);
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                System.out.println("系统错误:"+e);
            }

        }
        return resultString;
    }

}

使用

如需要发送POST请求,调用sendPost()方法

// 例子
// 定义接口路径
String url = “接口路径”
// 定义或传入参数
Object RequestBody = “参数”
// 其中Object指带不同类型的参数,如String Integer等等
// String RequestBody = “参数”
// 调用,其中HttpClientUtil为该工具类文件名称
String result=HttpClientUtil.sendGet(url,RequestBody);
// 打印结果
System.out.println(result);

如果需要发送Get请求,调用sendGet()方法

// 例子
// 定义接口路径
String url = “接口路径”
// 定义或传入参数,如有多个参数直接添加到map集合
Map<String,String> map =new HashMap<>();
map.put("key1",value1);
map.put("key2",value2);
// 调用,其中HttpClientUtil为该工具类文件名称
String result=HttpClientUtil.sendGet(url,map);
// 打印结果
System.out.println(result);

结语

以上为apache httpClient的工具类运用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值