springboot中配置restTemplate及简单使用

本文介绍如何在Spring Boot项目中使用RESTful风格进行API开发,包括引入依赖、配置RestTemplate Bean、封装HTTP请求工具类及示例代码。

一、引入web的starter

确保classpath中含有

compile("org.springframework.boot:spring-boot-starter-web")

二、配置restTemplate的Bean

    @Bean
    public RestTemplate restTemplate() {
        RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder();
        return restTemplateBuilder.build();
    }

三、自己简单封装的工具类

package com.kingboy.common.utils.restTemplate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @Author kingboy
 * @Date 2017/7/21 下午3:19
 * @Description RestClient is used to http请求
 */
@Component
public class RestKingClient {

    @Resource
    RestTemplate restTemplate;

    /**
     * get
     * @param url 请求地址
     * @param param  参数
     * @param returnClass 返回类型
     * @return
     */
    public <T> T get(String url, Class<T> returnClass, Map<String, ?> param) {
        return restTemplate.getForObject(url, returnClass, param);
    }


    /**
     * post
     * @param url 请求地址
     * @param param 参数
     * @param returnClass 返回类型
     * @param header 自定义的头信息
     * @return
     */
    public <E> E post(String url, E param, Class<E> returnClass, Map<String, String> header) {
        HttpHeaders headers = new HttpHeaders();
        header.forEach((o1, o2) -> headers.set(o1, o2));
        HttpEntity<E> httpEntity = new HttpEntity<E>(param,headers);
        return restTemplate.postForObject(url, httpEntity, returnClass);
    }


    /**
     * post
     * @param url 请求地址
     * @param param 参数
     * @param returnClass 返回类型
     * @return
     */
    public <E> E postByDefault(String url, E param, Class<E> returnClass) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept", "application/json");
        HttpEntity<E> httpEntity = new HttpEntity<E>(param,headers);
        return restTemplate.postForObject(url, httpEntity, returnClass);
    }


}

四、使用示例模拟

public class User {
    private String id;

    private String telephone;

    private String password;

    //setter,getter
}
package com.kingboy.sso.controller.rest;

import com.kingboy.common.utils.apiresult.ApiResult;
import com.kingboy.common.utils.restTemplate.RestKingClient;
import com.kingboy.ssoservice.domain.user.User;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author kingboy
 * @Date 2017/7/21 下午2:04
 * @Description RestTemplateController is used to 测试RestTemplate
 */
@RestController
@RequestMapping("/Rest")
public class RestTemplateController {

    @Resource
    private RestKingClient restKingClient;

    /**
     * 通过Get提供信息
     * @return
     */
    @GetMapping("/GetUser")
    public User getUserForRest() {
        //模拟假数据
        return new User(1, "telephone", "password");
    }

    /**
     * 测试Get方式
     * @param telephone
     * @param password
     * @return
     */
    @GetMapping("/GetUserFromRest/{telephone}/{password}")
    public ApiResult getUserByRest(@PathVariable String telephone, @PathVariable String password) {
        Map<String, String> param = new HashMap<>(2);
        param.put("telephone", telephone);
        param.put("password", password);
        //参数仅是演示用途
        User user = restKingClient.get("http://localhost:8080/Rest/GetUser", User.class, param);
        return ApiResult.success(user);
    }

    /**
     * 通过POST提供信息
     * @return
     */
    @PostMapping("/PostUser")
    public User postUserForRest(@RequestBody User user,@RequestHeader String Token) {
        //模拟假数据
        return new User(1, user.getTelephone(), user.getPassword());
    }

    /**
     * 测试POST方式
     * @param telephone
     * @param password
     * @return
     */
    @GetMapping("/PostUserFromRest/{telephone}/{password}")
    public ApiResult postUserByRest(@PathVariable String telephone, @PathVariable String password) {
        //设置头信息
        Map<String, String> headers = new HashMap<>();
        headers.put("ContentType", "application/json");
        headers.put("Token", "mytoken");
        //设置Body
        User param = new User(null, telephone, password);
        User user = restKingClient.post("http://localhost:8080/Rest/PostUser", param, User.class,headers);
        return ApiResult.success(user);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值