RestTemplate与HuTool-httpclient 远程调用技术使用对比以及坑

在后台对接其他系统的采用RESTAPI的方式来调度的话 ,那么从后台出发完成调度,简单的使用了restTemplate技术Hutool-httpclinet 来做了简单的demo。

RestTemplate

restTemplate是基于spring原生代码的调用机制。使用起来还是比较方便的。基于表单一定要使用

MultiValueMap<String, Object> 这个Map LinkHashMap是不行的。

public void testController(){
            try {
                RestTemplate  restTemplate = new RestTemplate();
                HttpHeaders headers  = new HttpHeaders();
                
                // 请求头相关参数可以set亦可以以map的方式add进去
                headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
                //headers.add( "content-Type","application/x-www-form-urlencoded");
                MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
                //接口参数
                map.add("user","admin");
                map.add("pwd","admin");

                String url = "http://192.168.0.123/api/getToken";
                HttpEntity<MultiValueMap<String, Object>> param = new HttpEntity<>(map, headers);
                ResponseEntity<String> response = restTemplate.postForEntity(url, param, String.class);

                String body = response.getBody();
                System.out.println(body);

            } catch (RestClientException e) {
                e.printStackTrace();
            }

HuTool-httpclient调用

hutool工具包官网的表述说是对原生java的远程调用API做了基本封装,满足日常使用,但是我发现在使用post调用的时候,以表单数据发送参数会有一个奇怪的坑

因为.form()是一个重载方法,可以单个传键值对,亦可以Map<String,Object> 如果一个map传过去不好使,那就单个form多调几次

 public void HTnet (){
           HashMap<String, Object> paramMap = new HashMap<>();
           paramMap.put("user","admin");
           paramMap.put("pwd","admin");
           String url = "http://192.168.0.123:8080/api/getToken";
            HttpResponse result = HttpRequest.post(url).
                    header("Content-Type", "application/x-www-form-urlencoded").
                   form("user","admin").form("pwd","admin").
                           //form(paramMap).
                    timeout(20000).execute();
            String body = result.body();
            System.out.println("body = " + body);


版权声明:本文为weixin_51738757原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。