HttpClient工具类调用url实例,附源码(一)

导读:本篇文章讲解 HttpClient工具类调用url实例,附源码(一),希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

问题背景

项目中经常会用到调用别人的url,除了postman,可以使用httpclient进行调用,封装一个httpclient进行使用
注意事项:

HttpClient工具类调用url实例,附源码(一)

HttpClient内外访问外网,添加代理(二)

项目创建

1 引入pom依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.6</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.yg</groupId>
    <artifactId>thirdTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>thirdTest</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
            <exclusions>
                <exclusion>
                    <artifactId>commons-codec</artifactId>
                    <groupId>commons-codec</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.62</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

2 启动类

package com.yg.thirdtest;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ThirdTestApplication {

    public static void main(String[] args) {
        SpringApplication.run(ThirdTestApplication.class, args);
    }

}

3 使用httpcilent调用url

package com.yg.thirdtest.controller;

import com.alibaba.fastjson.JSONObject;
import com.yg.thirdtest.dto.CallbackThirdDTO;
import com.yg.thirdtest.utils.HttpClientPoolUtil;
import com.yg.thirdtest.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Author suolong
 * @Date 2022/2/17 17:10
 * @Version 1.5
 */
@Slf4j
@RestController
@RequestMapping("/third")
public class CallbackThirdController {

    @Resource
    private HttpClientPoolUtil httpClientPoolUtil;

    @PostMapping("/callbackThird")
    public String callbackThird(@RequestBody CallbackThirdDTO callbackThirdDTO) throws Exception {

        if (callbackThirdDTO == null) {
            return "CallbackThirdDTO is null";
        }
        log.info("CallbackThirdDTO: {}", callbackThirdDTO);
        // String callback = computeDTO.getCallback()+"?file_id="+computeDTO.getFileId();
        JSONObject jsonObject = httpClientPoolUtil.postForJsonObject(callbackThirdDTO.getCallback(), JsonUtils.objectToJson(callbackThirdDTO));
        if (jsonObject == null) {
            return "Callback connect failed";
        }
        log.info("jsonObject: {}", jsonObject);
        return "SUCCESS";
    }
}

4 url地址中接收请求

package com.yg.thirdtest.controller;

import com.yg.thirdtest.dto.CallbackThirdDTO;
import com.yg.thirdtest.dto.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.ws.Response;


/**
 * @Author suolong
 * @Date 2022/4/3 14:49
 * @Version 1.5
 */
@RestController
@RequestMapping("/third")
@Slf4j
public class thirdContoller {

    @PostMapping("/test")
    public ResultVO<String> third(@RequestBody CallbackThirdDTO callbackThirdDTO) {
        log.info("CallbackThirdDTO: {}", callbackThirdDTO);
        return ResultVO.success("success");
    }

}

5 请求类

package com.yg.thirdtest.dto;

import lombok.*;

/**
 * @Author suolong
 * @Date 2022/2/17 16:44
 * @Version 1.5
 */
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class CallbackThirdDTO {
    private Long customerId;
    private String fileId;
    private String itemCode;
    private String callback;
    private String globalId;
}

6 响应代码

package com.yg.thirdtest.dto;

public class ResponseCode {

    /**
     * 表明该请求被成功地完成,所请求的资源发送到客户端。
     */
    public static final String SUCESS = "200";

    /**
     * 系统执行错误
     */
    public static final String FAIL = "500";


    /**
     * 系统执行错误
     */
    public static final String NEEDLOGIN = "401";

}

7 响应类

package com.yg.thirdtest.dto;


import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

import java.io.Serializable;


/**
 * @author : suolong
 * date : 2022/2/12 14:34
 */
@Builder
@Data
@NoArgsConstructor
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResultVO<T> implements Serializable {
    private static final long serialVersionUID = 7437203838526425744L;

    private T data;
    /**
     * 错误码
     */
    private String code;
    /**
     * 错误信息
     */
    private String msg;

    /**
     * @Caption
     * @Param
     * @Return
     */
    private String globalId;

    public ResultVO(T data, String code, String msg, String globalId) {
        this.data = data;
        this.code = code;
        this.msg = msg;
        this.globalId = globalId;
    }

    public static <T> ResultVO<T> success(T data) {
        return new ResultVO<T>(data, ResponseCode.SUCESS, "ok", null);
    }

    public static <T> ResultVO<T> success(T data, String globalId) {
        return new ResultVO<T>(data, ResponseCode.SUCESS, "ok", globalId);
    }

    public static <T> ResultVO<T> error(String message, String code) {
        return new ResultVO<>(null, code, message, null);
    }

    public static <T> ResultVO<T> error(String message, String code,String globalId) {
        return new ResultVO<>(null, code, message, globalId);
    }

    /**
     * 获取
     *
     * @return data
     */
    public T getData() {
        return this.data;
    }

    /**
     * 设置
     *
     * @param data
     */
    public void setData(T data) {
        this.data = data;
    }

    /**
     * 获取 错误码
     *
     * @return code 错误码
     */
    public String getCode() {
        return this.code;
    }

    /**
     * 设置 错误码
     *
     * @param code 错误码
     */
    public void setCode(String code) {
        this.code = code;
    }

    /**
     * 获取 错误信息
     *
     * @return msg 错误信息
     */
    public String getMsg() {
        return this.msg;
    }

    /**
     * 设置 错误信息
     *
     * @param msg 错误信息
     */
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

8 httpclient工具类,InitializingBean接口只有一个方法afterPropertiesSet,启动时会进行先调用进行初始化

package com.yg.thirdtest.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
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.methods.HttpRequestBase;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;

@Service
@Slf4j
public class HttpClientPoolUtil implements InitializingBean {
    private PoolingHttpClientConnectionManager poolConnManager;
    private RequestConfig requestConfig;
    private CloseableHttpClient httpClient;

    private static void config(HttpRequestBase httpRequestBase) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(20000)
                .setConnectTimeout(20000)
                .setSocketTimeout(20000).build();
        httpRequestBase.addHeader("Content-Type", "application/json;charset=UTF-8");
        httpRequestBase.setConfig(requestConfig);
    }

    private void initPool() {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register(
                    "http", PlainConnectionSocketFactory.getSocketFactory()).register(
                    "https", sslsf).build();
            poolConnManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            poolConnManager.setMaxTotal(500);
            poolConnManager.setDefaultMaxPerRoute(500);

            int socketTimeout = 1200000;
            int connectTimeout = 100000;
            int connectionRequestTimeout = 100000;
            requestConfig = RequestConfig.custom().setConnectionRequestTimeout(
                    connectionRequestTimeout).setSocketTimeout(socketTimeout).setConnectTimeout(
                    connectTimeout).build();
            httpClient = getConnection();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            e.printStackTrace();
        }
    }

    private CloseableHttpClient getConnection() {
        CloseableHttpClient httpClient = HttpClients.custom()
                .setConnectionManager(poolConnManager)
                .setDefaultRequestConfig(requestConfig)

                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, false))
                .build();
        return httpClient;
    }

    public JSONObject postForJsonObject(String url, String jsonStr) {
        log.debug("url = " + url + " ,  json = " + jsonStr);
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        try {

            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");

            StringEntity entity = new StringEntity(jsonStr, "UTF-8");
            entity.setContentType("application/json");
            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(entity);
            //发送post请求
            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                JSONObject result = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
                log.debug("request success cost = {}, result = {}", System.currentTimeMillis() - start, result);
                return result;
            } else {
                log.error("bad response: {}", JSONObject.parseObject(EntityUtils.toString(response.getEntity())));
            }
        } catch (Exception e) {
            log.error("=============[\"异常\"]======================, e: {}", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    public String post(String url, Map<String, Object> requestData) {
        HttpPost httpPost = new HttpPost(url);
        config(httpPost);
        StringEntity stringEntity = new StringEntity(JSON.toJSONString(requestData), "UTF-8");
        stringEntity.setContentEncoding(StandardCharsets.UTF_8.toString());
        httpPost.setEntity(stringEntity);
        return getResponse(httpPost);
    }


    public JSONArray post(String url, String jsonStr) {
        log.debug("url = " + url + " ,  json = " + jsonStr);
        long start = System.currentTimeMillis();
        CloseableHttpResponse response = null;
        JSONArray result = new JSONArray();
        try {
            // 创建httpPost
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "application/json");

            StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8.toString());
            entity.setContentType("application/json");
            entity.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
            httpPost.setEntity(entity);
            //发送post请求
            response = httpClient.execute(httpPost);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = JSONObject.parseArray(EntityUtils.toString(response.getEntity()));
                log.debug("request success cost = {}, result = {}", System.currentTimeMillis() - start, result);
                return result;
            } else {
                log.error("bad response, result: {}", EntityUtils.toString(response.getEntity()));
            }
        } catch (Exception e) {
            log.error("=============[\"异常\"]======================, e: {}", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public String get(String url) {
        HttpGet httpGet = new HttpGet(url);
        config(httpGet);
        return getResponse(httpGet);
    }

    private String getResponse(HttpRequestBase request) {
        CloseableHttpResponse response = null;
        try {

            response = httpClient.execute(request,
                    HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, StandardCharsets.UTF_8.toString());
            EntityUtils.consume(entity);

            return result;
        } catch (IOException e) {
            log.error("send http error", e);
            return "";
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }


        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initPool();
    }
}

10 Json工具类

package com.yg.thirdtest.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * @author : moye
 * date : 2022/1/24 11:05
 */
@Slf4j
public class JsonUtils {
    /**
     * 定义jackson对象
     */
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     * @param data
     * @return
     */
    public static String objectToJson(Object data) {
        try {
            return MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 将json结果集转化为对象
     *
     * @param jsonData json数据
     * @param beanType 对象中的object类型
     * @return
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) throws JsonProcessingException {
        try {
            return MAPPER.readValue(jsonData, beanType);
        } catch (JsonProcessingException e) {
            log.error("json结果集转化为对象异常:{}", e.getLocalizedMessage());
            throw e;
        }
    }

    /**
     * 将json数据转换成pojo对象list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T>List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            return MAPPER.readValue(jsonData, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}

11 端口设置application

server.port=1994

12 整体项目文件目录
HttpClient工具类调用url实例,附源码(一)

代码测试

1 启动项目,因为在本地,使用postman调用http://localhost:1994/third/callbackThird
HttpClient工具类调用url实例,附源码(一)

{
	"customerId": 123,
    "fileId": "abc",
    "itemCode": "qwe",
    "globalId": "asasdf",
    "callback": "http://localhost:1994/third/test"
}

2 根据callback的url地址,会使用httpclient去访问url,日志打印,可以看到调用url成功了,postman也返回成功
HttpClient工具类调用url实例,附源码(一)
HttpClient工具类调用url实例,附源码(一)

总结

  • 这是调用url常用的方式,如果是nacos注册中心,还可以使用微服务feignclient调用,在我的其他文章中可以进行参考

作为程序员第 96 篇文章,每次写一句歌词记录一下,看看人生有几首歌的时间,wahahaha …
HttpClient工具类调用url实例,附源码(一)HttpClient工具类调用url实例,附源码(一)HttpClient工具类调用url实例,附源码(一)

Lyric: 来不及听见

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

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

(0)
小半的头像小半

相关推荐

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