RestTemplate

6 篇文章 0 订阅
3 篇文章 0 订阅

一.简介

是Spring用于同步client端的核心类,简化了与http服务的通信,并满足RestFul原则,程序代码可以给它提供URL,并提取结果。默认情况下,RestTemplate默认依赖jdk的HTTP连接工具。当然你也可以 通过setRequestFactory属性切换到不同的HTTP源,比如Apache HttpComponents、Netty和OkHttp。。RestTemplate并没有限定Http的客户端类型,而是进行了抽象,目前常用的3种都有支持:

  • HttpClient
  • OkHttp
  • JDK原生的URLConnection(默认的)

二.在springBoot中使用

1.创建配置类

HttpClientConfig.java

package com.miracle.location.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

/**
 * Title:
 * Description:
 * Company:东软集团股份有限公司(NEUSOFT)
 * Department: 医疗IT事业部开发部
 *
 * @Author: Miracle
 * email: 350148888@qq.com
 */
@Configuration
public class HttpClientConfig {
    // 想容器中添加 RestTemplate
    @Bean
    public RestTemplate restTemplate() {

        /**
         *  这里可以选择底层实现(有三种):
         *     HttpClient
         *     OkHttp
         *     JDK原生的URLConnection(默认的)
         */
        // 创建 JDK原生的URLConnection(默认的)
        RestTemplate restTemplate = new RestTemplate();
        // 解决中文乱码
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
}

2.使用

这里使用springtest进行单元测试

package com.miracle;

import com.miracle.pojo.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo2ApplicationTests {

    @Autowired
    private RestTemplate restTemplate;

    @Test
    public void test1(){
        // 第一个参数:发送get请求的url,第二个参数:当服务器返回json,使用bean对象接收
        User user = restTemplate.getForObject("http://localhost:8080/hello/aaa", User.class);
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>" + user);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值