http请求工具类

17 篇文章 0 订阅
4 篇文章 0 订阅

http请求工具类

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nancal.workflow.common.constant.HttpRequestConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class WfHttpRequestUtils {

    public static final String RESPONSE_STATUS = "responseStatus";
    public static final String RESPONSE_BODY = "responseBody";

    /**
     * 获取外部请求返回值
     * @param address 请求地址
     * @param requestType 请求类型
     * @param requestParam 直接请求参数
     * @param variables 额外参数
     * @return
     */
    public static String getResponseBody(String address, String requestType, String requestParam, Map<String, Object> variables) {
        Map<String, Object> map = executeRequest(address, requestType, requestParam, variables);
        String body = (String)map.get(RESPONSE_BODY);
        return body;
    }

    public static Map<String, Object> getResponseMap(String address, String requestType, String requestParam, Map<String, Object> variables) {
        Map<String, Object> map = executeRequest(address, requestType, requestParam, variables);
        return map;
    }

    private static Map<String, Object> executeRequest(String address, String requestType, String requestParam, Map<String, Object> variables) {
        JSONObject jsonObject = new JSONObject();
        if (StrUtil.isNotBlank(requestParam)) {
            JSONObject paramJson = JSONUtil.parseObj(requestParam);
            Iterator<String> keyIter = paramJson.keySet().iterator();
            while (keyIter.hasNext()) {
                String key = keyIter.next();
                Object value = paramJson.get(key);
                jsonObject.putIfAbsent(key, value);
            }
        }
        if (CollectionUtil.isNotEmpty(variables)) {
            Iterator<String> keyIter = variables.keySet().iterator();
            while (keyIter.hasNext()) {
                String key = keyIter.next();
                Object value = variables.get(key);
                jsonObject.putIfAbsent(key, value);
            }
        }
        String finalParams = JSONUtil.toJsonStr(jsonObject);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = null;
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            token = request.getHeader("token");
        }
        log.info("根据外部地址获取人员信息参数, 地址:{}, 类型: {}, 参数: {}, token: {}", address, requestType, finalParams, token);
        HttpRequest httpRequest = null;
        if (HttpRequestConstant.POST.equals(requestType)) {
            httpRequest = HttpRequest.post(address);
        } else if (HttpRequestConstant.GET.equals(requestType)) {
            httpRequest = HttpRequest.get(address);
        } else if (HttpRequestConstant.DELETE.equals(requestType)) {
            httpRequest = HttpRequest.delete(address);
        }
        Map<String, Object> resultMap = new HashMap<>();
        String responseBody = null;
        Boolean responseStatus = false;
        if (httpRequest != null) {
            httpRequest.setFollowRedirects(true);
            HttpResponse response = null;
            try {
                response = httpRequest.header("Content-Type", "application/json")
                        .header("token", token)
                        .body(finalParams)
                        .execute();
                String body = response.body();
                responseStatus = response.isOk();
                if (responseStatus && StrUtil.isNotBlank(body)) {
                    log.info("外部接口返回: {}", body);
                    responseBody = body;
                }

            } catch (Exception ex) {
                log.error("外部接口调用失败:{}", ex.getMessage());
                ex.printStackTrace();
            }
        }
        resultMap.put(RESPONSE_BODY, responseBody);
        resultMap.put(RESPONSE_STATUS, responseStatus);
        return resultMap;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中有多种HTTP请求工具类可供使用,其中一种是http-request。它基于URLConnection实现,不依赖于HttpClient。使用http-request发送GET请求示例如下: 1. 引入依赖: ``` <dependency> <groupId>com.github.kevinsawicki</groupId> <artifactId>http-request</artifactId> <version>5.6</version> </dependency> ``` 2. 发送GET请求获取响应报文: ```java String response = HttpRequest.get("http://www.baidu.com").body(); System.out.println("Response was: " + response); ``` 3. 发送GET请求获取响应码: ```java int code = HttpRequest.get("http://google.com").code(); ``` 除了http-request,还有其他一些常用的HTTP请求工具类,比如HttpUtil。使用HttpUtil发送GET请求的示例代码如下: ```java // 最简单的HTTP请求,自动判断编码 String result1 = HttpUtil.get("https://www.baidu.com"); // 自定义请求页面的编码 String result2 = HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8); // 传入http参数,参数会自动做URL编码,拼接在URL中 HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result3 = HttpUtil.get("https://www.baidu.com", paramMap); ``` 如果需要发送POST请求,可以使用HttpUtil的post方法,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>(); paramMap.put("city", "北京"); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 另外,如果需要文件上传,可以将参数中的键指定为"file",值设为文件对象即可,示例代码如下: ```java HashMap<String, Object> paramMap = new HashMap<>();paramMap.put("file", FileUtil.file("D:\\face.jpg")); String result = HttpUtil.post("https://www.baidu.com", paramMap); ``` 以上是一些常用的Java HTTP请求工具类,你可以根据具体需求选择适合的工具类来发送HTTP请求。请问您还有其他相关问题吗? 相关问题: 1. Java中还有哪些常用的HTTP请求工具类? 2. 如何处理HTTP请求的返回结果? 3. 如何设置HTTP请求的超时时间?

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值