Java发送http、https请求

版权声明:本文为博主原创文章,未经博主允许不得转载 https://blog.csdn.net/weixin_43835717/article/details/90342379

使用tools-httpclient即可在项目中快速发送HTTP/HTTPS请求

项目使用方式:

  1. 添加依赖:
<dependency>
    <groupId>cn.gjing</groupId>
    <artifactId>tools-httpclient</artifactId>
    <version>1.0.1</version>
</dependency>
  1. 需要使用的接口中直接使用:
  • HTTP请求(GET案例)
public static void main(String[] args) {    
    Map<String, String> map = new HashMap<>(16);
    map.put("a", "参数a");
    map.put("b", "参数b");
    //发送http请求
    String result = HttpClient.get("http://127.0.0.1:8080/test", map, String.class);
    System.out.println(result);
}
  • HTTPS请求(POST案例)
public static void main(String[] args) {    
    Map<String, String> map = new HashMap<>(16);
    map.put("a", "参数a");
    map.put("b", "参数b");
    //发送https请求
    Map result = HttpClient.post("https://127.0.0.1:8080/test", map, Map.class);
    System.out.println(result.toString());
}
  • DELETE案例
public static void main(String[] args) {    
    ResultBean result = HttpClient.delete("http://127.0.0.1:8080/test/1", ResultBean.class);
    System.out.println(result.toString());
}
  • PUT案例
public static void main(String[] args) {    
    Integer result = HttpClient.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字符串

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

@GetMapping("/test")
public Integer test() {
    return 1111;
}

调用方

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

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


  1. UrlUtil工具类
  • urlAppend(用于URL地址直接带参)
    public static void main(String[] args) {
        String url = "http://127.0.0.1:8080/";
        Object[] param = {1, 2, 3, 4};
        System.out.println(UrlUtil.urlAppend(url, param));
    }
    输出结果为:http://127.0.0.1:8080/1/2/3/4/
  • paramUnicodeSort(参数按照字段名的Unicode码从小到大排序(字典序))
    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>(16);
        map.put("a", "参数1");
        map.put("b", "参数2");
        /*
            该方法带三个参数,分别为:
            paramMap: 参数
            urlEncode: 是否进行URL encode
            keyToLower: 转换后的参数的key值是否转为小写
         */
        System.out.println(UrlUtil.paramUnicodeSort(map, false, false));
    }
    输出结果为:a=参数1&b=参数2
  • urlParamToMap(将URL地址后带的参数转成map)
    public static void main(String[] args) {
        String url = "http://127.0.0.1:8080?a=2&b=2";
        System.out.println(UrlUtil.urlParamToMap(url));
    }
    输出结果为:{a=2, b=2}

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

猜你喜欢

转载自blog.csdn.net/weixin_43835717/article/details/90342379