• 【Java SE】http请求RestTemplate


    【Java SE】http请求RestTemplate

    RestTemplate对象

    @Configuration
    public class RestTemplateConfiguration {
        @Bean
        public RestTemplate restTemplate() {
            HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
            httpRequestFactory.setConnectionRequestTimeout(120 * 1000);
            httpRequestFactory.setConnectTimeout(2 * 60 * 1000);
            httpRequestFactory.setReadTimeout(10 * 60 * 1000);
            return new RestTemplate(httpRequestFactory);
        }
    }

    简单例子

    public String getJsonDataFromUrl(String url, String method) {
        String json;
        if ("get".equals(method.toLowerCase())) {
            json = restTemplate.getForObject(url, String.class);
        } else {
            MultiValueMap<String, Object> request = new LinkedMultiValueMap<>();
            if (url.contains("?")) {
                int index = url.indexOf("?");
                String paramStr = url.substring(index + 1);
                url = url.substring(0, index);
                String[] itemArray = paramStr.split("&");
                for (String item : itemArray) {
                    String[] pairArray = item.split("=");
                    request.add(pairArray[0], pairArray[1]);
                }
            }
            json = restTemplate.postForObject(url, request, String.class);
        }
        return json;
    }
  • 相关阅读:
    已知二叉树的前序遍历、中序遍历,求后序遍历
    排序算法
    应用层
    运输层
    mysql分页查询
    mysql 性能分析及explain用法
    数据库SQL优化
    MATLAB GUI设计(1)
    路径选择
    Python itchat库(1)
  • 原文地址:https://www.cnblogs.com/yangchongxing/p/16313520.html
Copyright © 2020-2023  润新知