apache httpClient工具类

导读:本篇文章讲解 apache httpClient工具类,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

前言

记录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的工具类运用

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/101164.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!