1. RestTemplate : 获取网页中信息的方法
使用Java程序发送http请求(get,post,delete,put)
底层使用:OkHttpClient(Apache)灵活切换
RestTemplate提供三类API
- 简单请求,直接获取响应体
- 发送简单请求,获取响应所有内容
- 完整发送一个请求,获取一个完整响应
Controller层
@RestController
@RequestMapping(path = "/rest/")
public class RestTemplateController {
@Autowired
private RedisTemplate redisTemplate;
@GetMapping(path = "/aa")
public Map<String,String> test1(){
Map<String,String> map= Maps.newHashMap();
map.put("name","zhangsan");
return map;
}
}
测试类
public void test4(){
//通过RestTemplate来进行读取网页中的信息
String url="http://localhost:8081/rest/aa";
String forObject = restTemplate.getForObject(url, String.class, new HashMap<>());
System.out.println(forObject);
}
在Spring 中使用要在config类中定义
配置类中的配置
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
- 三种获取网页中信息的方法
public class TestRestTemple extends BaseTest {
@Autowired
private RestTemplate restTemplate;
@Test
public void test1(){
//通过RestTemplate来进行读取网页中的信息
String url="http://www.baidu.com";
ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
System.out.println(entity);
}
@Test
public void test2(){
//通过RestTemplate来进行读取网页中的信息
String url="http://www.baidu.com";
String object = restTemplate.getForObject(url, String.class);
System.out.println(object);
}
@Test
public void test3(){
//通过RestTemplate来进行读取网页中的信息
String url="http://www.baidu.com";
ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
String body = entity.getBody();
//获取响应体
System.out.println(body);
System.out.println(entity.getStatusCode());//获取响应的参数 200
}
注:需要导入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>4.4.1</version>
</dependency>
2. RedisTemplate:用于往redis中存入数据
- 例:
@SpringBootTest
public class TestRedis {
/**
*从spring容器中获取RedisTemplate对象
*/
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
*往Redis存入数据测试
*/
@Test
public void test01() {
redisTemplate.opsForValue().set("zhangsan", "123");
String s = redisTemplate.opsForValue().get("zhangsan");
System.out.println(s);
}
}