【Http客户端-1】Http客户端-RestTemplate的使用实例代码

http 客户端的工具越来越多,每次使用的时候又各有特点,所以在这里总结下各个http 客户端工具的使用,java代码如下。

常见的http客户端工具有这些:httpClient, okHttp, RestTemplate,jesryClient

【Http客户端】Http客户端-RestTemplate的使用实例代码

今天我们说说 RestTemplate工具

1. 构建一个RestTemplate 的单例bean

当然你也可以直接在方法内部每次使用的时候 new 一个RestTemplate对象。

比如 RestTemplate restTemplate = new RestTemplate(); 也是可以的

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory simpleClientHttpRequestFactory) {
        return new RestTemplate(simpleClientHttpRequestFactory);
    }

    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(3000);
        factory.setReadTimeout(30000);
        return factory;
    }
}

2. 使用RestTemplate 

2.1 RestTemplate GET请求示例代码

header参数的设置

requestParameter参数的设置

response数据的解析

 void testSendGetHttp() {
        // http请求模板
        RestTemplate restTemplate = new RestTemplate();

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("clientId", "123123");
        headers.add("secret", "321321");

        // url
        String url = "https://example.com/user";

        // get请求构造url
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(url)
                .queryParam("username", "张三")
                .queryParam("email", "");
        String path = builder.build().toUri().toString();
        log.info("path: {}", path);  // 输出https://example.com/user?username=张三&email=
        // 封装http实体
        HttpEntity entity = new HttpEntity<>(headers);

        // 发送请求
        ResponseEntity response = restTemplate.exchange(path, HttpMethod.GET, entity, String.class);
        log.info("response body: {}", response.getBody());

    }

2.2 RestTemplate POST请求示例代码

header参数的设置

requestBody参数的设置

response数据的解析

    @Override
    public boolean registerAccount1(String username, String password, String captcha) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", Base64Utils.createBasicHeader(appKey, appSecret));
        log.info(" Authorization: {}", headers.get("Authorization").toString());

        // 请求参数,一个list里面装着map
        List> list = new ArrayList<>();
        Map departmentUserMap = new HashMap<>();
        departmentUserMap.put("department", "[\"testDepartment\"]");
        departmentUserMap.put("post", "管理员");
        departmentUserMap.put("recursive", "true");
        list.add(departmentUserMap);

        // 封装http实体
        HttpEntity>> httpEntity = new HttpEntity<>(list, headers);

        // 发送请求
        ResponseEntity response = restTemplate.exchange(AccountConstants.URL_ACCOUNT_POST_REGISTER, HttpMethod.POST,
                httpEntity, Map.class);

        log.info("response body: {}", response.getBody());

        return false;
    }


    @Override
    public boolean registerAccount2(String username, String password, String captcha) {
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", Base64Utils.createBasicHeader(appKey, appSecret));
        log.info(" Authorization: {}", headers.get("Authorization").toString());

        // 请求参数,一个list里面装着map
        Map registerMap = new HashMap<>();
        registerMap.put("identity", username);
        registerMap.put("password", password);
        registerMap.put("captcha", captcha);

        // 封装http实体
        HttpEntity> httpEntity = new HttpEntity<>(registerMap, headers);

        ParameterizedTypeReference> typeRef = new ParameterizedTypeReference>() {
        };

        // 发送请求
        ResponseEntity> response = restTemplate.exchange(AccountConstants.URL_ACCOUNT_POST_REGISTER, HttpMethod.POST,
                httpEntity, typeRef);

        log.info("response body: {}", response.getBody());

        return false;
    }


你可能感兴趣的:(http,网络协议,java)