美文网首页
hutool之HttpUtil网络请求工具

hutool之HttpUtil网络请求工具

作者: AC编程 | 来源:发表于2023-07-05 13:36 被阅读0次

一、测试代码


import cn.hutool.core.text.UnicodeUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.Gson;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class Test {
    public static void main(String[] args) {
        requestToken();
    }

    public static String requestToken() {
        try {
            String url = "https://alanchen.com/auth/getToken/V2";

            HttpRequest request = HttpUtil.createPost(url);
            request.header("PartnerCode", "testCode");

            Map<String, String> param = new HashMap();
            param.put("partnerCode", "testCode");
            param.put("partnerSecret", "secret");

            Gson gson = new Gson();
            String body = gson.toJson(param);
            request.body(body);

            HttpResponse execute = request.execute();
            if (!execute.isOk()) {
                log.error("请求token失败,body={},execute={}", execute.body(), execute);
                throw new RuntimeException(execute.body());
            }
            String res = UnicodeUtil.toString(execute.body());
            JSONObject jsonObject = JSONUtil.parseObj(res, true);
            AuthTokenResResult resultObj = jsonObject.toBean(AuthTokenResResult.class, true);
            log.info("requestToken,resultObj={}", resultObj);
            if (resultObj.getCode() != 200) {
                log.error("获取token失败,code={},msg={},result={}", resultObj.getCode(), resultObj.getMsg(), resultObj);
                throw new RuntimeException("获取token失败,code=" + resultObj.getCode() + ",msg=" + resultObj.getMsg());
            }

            if (resultObj.getData() == null) {
                log.error("获取token为空,code={},msg={},result={}", resultObj.getCode(), resultObj.getMsg(), resultObj);
                throw new RuntimeException("获取token为空,code=" + resultObj.getCode() + ",msg=" + resultObj.getMsg());
            }

            return resultObj.getData().getToken();
        } catch (Exception e) {
            log.error("requestToken失败,msg={}", e.getMessage());
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    @Data
    public class AuthTokenResResult {

        private int code;

        private String msg;

        private AuthToken data;

        private long count;
    }

    @Data
    public class AuthToken {

        private String token;

        private long expireAt;
    }
}

二、代码片段

 // 设置请求体参数
String requestBody = "{\"param1\": \"value1\", \"param2\": \"value2\"}";
httpRequest.body(requestBody)
        .setHeader("Content-Type", "application/json")
        .timeout(20000); // 设置超时时间为20秒


// 设置请求参数
httpRequest.setQueryParam("param1", "value1")
          .setHeader("User-Agent", "Hutool")
          .timeout(20000); // 设置超时时间为20秒

相关文章

网友评论

      本文标题:hutool之HttpUtil网络请求工具

      本文链接:https://www.haomeiwen.com/subject/usdkudtx.html