Hutool-http

  • Maven
<dependency>
    <groupId>cn.hutool</groupId>
    <artifactId>hutool-all</artifactId>
    <version>5.7.9</version>
</dependency>
  • 笔记
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import java.util.Arrays;

public class Hutool_http {

    public static void main(String[] args) {
        //----------------------------  HttpUtil get  ----------------------------
        String result = HttpUtil.get("https://api.doctorxiong.club/v1/fund/position?code=003634");
        System.out.println(JSONObject.parseObject(result));

        JSONObject json = new JSONObject();
        json.put("code", "003634");
        String result = HttpUtil.get("https://api.doctorxiong.club/v1/fund/position",json);
        System.out.println(JSONObject.parseObject(result));

        //----------------------------  HttpUtil post  ----------------------------
        JSONObject json = new JSONObject();
        json.put("fundType", Arrays.asList("zs"));
        json.put("sort","z");
        json.put("fundCompany", Arrays.asList("80000248"));
        json.put("pageIndex",1);
        json.put("pageSize",5);
        json.put("Content-Type","application/json;charset=UTF-8");
        String result = HttpUtil.post("https://api.doctorxiong.club/v1/fund/rank", JSONObject.toJSONString(json));
        System.out.println(JSONObject.parseObject(result));

        //----------------------------  HttpRequest get  ----------------------------
        HttpResponse httpResponse = HttpRequest.get("https://api.doctorxiong.club/v1/fund/position?code=003634").execute();
        System.out.println(httpResponse);

        //----------------------------  HttpRequest post  ----------------------------
        JSONObject json = new JSONObject();
        json.put("fundType",Arrays.asList("zs"));
        json.put("sort","z");
        json.put("fundCompany",Arrays.asList("80000248"));
        json.put("pageIndex",1);
        json.put("pageSize",10);
        HttpResponse httpResponse = HttpRequest.post("https://127.0.0.1:8100/service/test")
                //.header(Header.USER_AGENT, "Hutool http")//头信息,多个头信息多次调用此方法即可
                //.setHttpProxy("192.168.1.66", 8032) //配置代理转发
                .body(JSONObject.toJSONString(json))
                .contentType("application/json;charset=UTF-8")
                .timeout(3000)
                .execute();
        System.out.println("--httpResponse--" + httpResponse);
        if(200 == httpResponse.getStatus() ){
            JSONObject responseBody = JSONObject.parseObject(httpResponse.body());
            System.out.println("--responseBody--" + responseBody);
        }else {
            System.out.println("请求失败。");
        }

    }

}

  

posted on 2021-08-27 18:08  陌生街中吹起褪色故梦  阅读(1069)  评论(0编辑  收藏  举报