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

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

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

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

RestTemplate

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

MultiValueMap 这个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 map = new linkedMultiValueMap<>();
                //接口参数
                map.add("user","admin");
                map.add("pwd","admin");

                String url = "http://192.168.0.123/api/getToken";
                HttpEntity> param = new HttpEntity<>(map, headers);
                ResponseEntity 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 如果一个map传过去不好使,那就单个form多调几次

 public void HTnet (){
           HashMap 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);

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5685674.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存