RestTemplate 例子

RestTemplate是spring 定义的一套标准,可以使用多种方式实现,而这个例子,直接使用的默认的,主要为了演示里面常用的方法

此目的过于简单,所以直接把自己写的记录例子

还是基于微服务

启动eureka服务器

 

编写一个微服务,服务提供者,且向eureka服务器注册

#设置服务注册中心的URL,用于client和server端交流
eureka.client.service-url.defaultZone=http://admin:123@euk1.com:7001/eureka/

server.port=8080

spring.application.name=client

暴露的接口

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class MainController {

	
	@GetMapping("/getHi")
	public String getHi() {
		return "Hi";
	}
	

	@GetMapping("/getMap")
	public Map<String, String> getMap() {
		return Collections.singletonMap("name", "getMap");
	}
	
	@GetMapping("/getList")
	public List<String> getList() {
		return Collections.singletonList("getList");
	}
	
	@GetMapping("/getBean")
	public UserBean getBean() {
		return new UserBean("getBean", "test");
	}
	
	@GetMapping("/getParamBean")
	public UserBean getParamBean(String password) {
		return new UserBean("getBean", password);
	}
	@PostMapping("/postBean")
	public UserBean postBean() {
		return new UserBean("postBean", "test");
	}
	
	@PostMapping("/postParamBean")
	public UserBean postParamBean(String password) {
		return new UserBean("postParamBean", password);
	}
	
	/**
	 * 返回一个Url,
	 * 注意:response.addHeader("Location", uri.toString()); 
	 * 这行代码必须添加
	 * @param response
	 * @return
	 * @throws URISyntaxException
	 */
	@PostMapping("/postLocation")
	public URI postLocation(HttpServletResponse response) throws URISyntaxException {
		URI uri = new URI("https://www.baidu.com");
		// 下面这行代码必须添加,不然会返回null
		response.addHeader("Location", uri.toString());
		return uri;
	}
	
	
}

UserBean.java

public class UserBean {

	private String username;
	
	private String password;

	public UserBean() {}
	public UserBean(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

 

 

 

编写另一个微服务,服务调用者,且向eureka服务器注册,同时使用RestTemplate调用提供者的接口

配制文件与服务提供者相同,但要更换端口号

server.port=8090

调用测试类



import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
@RequestMapping("/rest-template")
public class RestTemplateController {

	@Autowired
	private RestTemplate restTemplate;
	
	/**
	 * RestTemplate自动处理url
	 * @return
	 */
	@GetMapping("/client")
	public String client() {
		String url = "http://client/getPort";
		return restTemplate.getForObject(url, String.class);
	}
	
	@SuppressWarnings("unchecked")
	@GetMapping("/testGetMap")
	public Map<String, String> testGetMap() {		
		String url ="http://client/getMap";
		return restTemplate.getForObject(url, Map.class);
	}
	
	@SuppressWarnings("unchecked")
	@GetMapping("/testGetList")
	public List<String> testGetList() {		
		String url ="http://client/getList";
		return restTemplate.getForObject(url, List.class);
	}
	
	@GetMapping("/testGetBean")
	public UserBean testGetBean() {		
		String url ="http://client/getBean";
		return restTemplate.getForObject(url, UserBean.class);
	}
	
	@GetMapping("/testGetParamBean")
	public UserBean testGetParamBean() {		
		String url ="http://client/getParamBean?password={1}";
		return restTemplate.getForObject(url, UserBean.class, "testGetParamBean");
	}
	
	@GetMapping("/testPostBean")
	public UserBean testPostBean() {		
		String url ="http://client/postBean";
		return restTemplate.postForObject(url, null, UserBean.class);
	}
	
	@GetMapping("/testPostParamBean")
	public UserBean testPostParamBean() {		
		String url ="http://client/postParamBean";

		Map<String, String> map = Collections.singletonMap("password", "testPostParamBean");
		return restTemplate.postForObject(url, map, UserBean.class);
	}
	
	@GetMapping("/testPostLocation")
	public UserBean testPostLocation(HttpServletResponse response) throws MalformedURLException, IOException {		
		String url ="http://client/postLocation";
		URI uri = restTemplate.postForLocation(url, null);
		response.sendRedirect(uri.toURL().toString());
		
		return null;
	}
	
	/**
	 * 自定义restTemplate请求拦载器
	 * @author Sam
	 *
	 */
	public static class Interceptor implements ClientHttpRequestInterceptor {
		@Override
		public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
				throws IOException {
			System.out.println(String.format("intercept uri : %s", request.getURI()));
			ClientHttpResponse response = execution.execute(request, body);
			System.out.println(response.getHeaders());
			return response;
		}
	}
}

UserBean.java 和上面的相同,拷贝一个过来就行

拦截器需要在声明RestTemplate时配制

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@Configuration
public class EurekaClientApplication {
	public static void main(String[] args) {
		SpringApplication.run(EurekaClientApplication.class, args);
	}
	
	@Bean
	@LoadBalanced // 添加ribbon
	public RestTemplate getRestTemplate() {
		RestTemplate restTemplate = new RestTemplate();
		// 自定义拦载器,在此处添加
		restTemplate.getInterceptors().add(new RestTemplateController.Interceptor());
		return restTemplate;
	}

} 

请求拦截器的测试结果

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值