Java-http工具类

13次阅读

共计 2211 个字符,预计需要花费 6 分钟才能阅读完成。

在项目中快速发起 http 请求

一、添加依赖

<dependency>
    <groupId>cn.gjing</groupId>
    <artifactId>tools-httpclient</artifactId>
    <version>1.0.2</version>
</dependency>

二、项目使用

1、HTTP 请求(GET 案例)

public static void main(String[] args) {HttpClient client = new HttpClient();
    Map<String, String> map = new HashMap<>(16);
    map.put("a", "参数 a");
    map.put("b", "参数 b");
    // 发送 http 请求
    String result = client.get("http://127.0.0.1:8080/test", map, String.class);
    System.out.println(result);
}

2、HTTPS 请求(POST 案例)

public static void main(String[] args) {HttpClient client = new HttpClient();
    Map<String, String> map = new HashMap<>(16);
    map.put("a", "参数 a");
    map.put("b", "参数 b");
    // 发送 https 请求
    Map result = client.post("https://127.0.0.1:8080/test", map, Map.class);
    System.out.println(result.toString());
}

3、DELETE 案例

public static void main(String[] args) {HttpClient client = new HttpClient(); 
    ResultBean result = client.delete("http://127.0.0.1:8080/test/1", ResultBean.class);
    System.out.println(result.toString());
}

4、PUT 案例

public static void main(String[] args) {HttpClient client = new HttpClient(); 
    Integer result = client.put("https://127.0.0.1:8080/test/2", Integer.class);
    System.out.println(result);
}

三、HttpClient 参数说明

必填项参数除外的任意参数不需要时可直接传 null

参数 描述
url 请求地址, 必填
queryMap 请求参数
headers 请求头
connectTimeout 请求超时时间,默认 5s
readTimeout 读超时时间,默认 10 秒
responseType 响应结果返回类型, 必填
jsonEntity Json 对象, Json 字符串对应的对象或者 map
jsonStr Json 字符串

响应结果 返回类型最好设置与目标方法一致,否则可能会出现转换异常,如下:

  • 目标方法
@GetMapping("/test")
public Integer test() {return 1111;}
  • 调用方
public static void main(String[] args) {HttpClient client = new HttpClient();
    Map result = client.get("http://127.0.0.1:8080/test", Map.class);
    System.out.println(result.toString());
}

由于目标方法返回的为 Integer 类型,不是 key,value 类型,故调用方使用 Map 接收会出现 转换异常

四、UrlUtil 工具类

1、urlAppend

Url 拼接, 返回结果格式如: http://xxx/param1/param2

    public static void main(String[] args) {
        String url = "http://127.0.0.1:8080/";
        Object[] param = {1, 2, 3, 4};
        UrlUtil.urlAppend(url, param);
    }

2、paramUnicodeSort

参数按照字段名的 Unicode 码从小到大排序(字典序), 得到的结果格式如: a= 参数 1 &b= 参数 2

    public static void main(String[] args) {Map<String, Object> map = new HashMap<>(16);
        map.put("a", "参数 1");
        map.put("b", "参数 2");
        UrlUtil.paramUnicodeSort(map, false, false);
    }

参数说明

参数 描述
paramMap 参数
urlEncode 是否进行 URL 编码
keyToLower 转换后的参数的 key 值是否要转为小写

3、urlParamToMap

将 URL 地址后带的参数转成 map

    public static void main(String[] args) {
        String url = "http://127.0.0.1:8080?a=2&b=2";
        UrlUtil.urlParamToMap(url);
    }

项目源代码可前往 GitHUb 查看:tools-httpclient

正文完
 0