一、引入依赖
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
二、配置类
RestTemplateConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
//@LoadBalanced
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
return new RestTemplate();
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(60000); // ms
factory.setConnectTimeout(60000); // ms
return factory;
}
}
三、post请求
1、post请求说明
RestTemplate的post请求包含两个主要方法:
postForObject():返回body对象
postForEntity():返回全部的信息,包括状态码,body,header
RestTemplate.java
参数和get请求的相比,就多了第二个参数(Object request),如果使用最后一个参数传参时,和get请求类似,request设置为null就可以,如果使用第二个参数传参时,就需要考虑request的类型,request参数类型必须是实体对象、MultiValueMap、HttpEntity对象的的一种,其他不可以!!!
- 实体对象传参时,被请求的接口方法上必须使用@RequestBody,接收参数为实体或者Map;
- HttpEntity传参时,取决于HttpEntity对象的第一个参数,可以为任何类型,包括HashMap;
- MultiValueMap传参时,接收参数使用注解@RequestBody时,使用一个String类型、名称随意,使用@RequestParam时,使用对应个数的String类型字符串,名称必须和map中的key相同;推荐使用@RequestParam
2、发送post请求,header设置,(发送对象)
import com.company.feishu.FeishuApplication;
import lombok.extern.slf4j.Slf4j;
import org.junit.Before;
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.http.*;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
/**
* 测试RestTemplate
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FeishuApplication.class)
@Slf4j
public class AuthTest {
@Autowired
private RestTemplate restTemplate;
//@Before //import org.junit.Before;
//@BeforeEach //import org.junit.jupiter.api.BeforeEach;
@Before
public void config() {
}
@Test
public void testPostFrom() {
// 请求地址
String url = "http://localhost/auth/testPostForm";
// 请求头设置,x-www-form-urlencoded格式的数据
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); //提交表单数据
// 提交表单数据参数设置
MultiValueMap map = new LinkedMultiValueMap<>();
map.add("param1", "参数1");
map.add("param2", "参数2");
// 组装请求体(指定第一个参数的泛型)
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
// postForObject发起请求
String str = restTemplate.postForObject(url, request, String.class);
System.out.println(str);
// postForEntity发起请求
// String.class指定返回的Body的类型
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
//ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);
System.out.println(responseEntity.getStatusCode().value());
System.out.println(responseEntity.getBody());
System.out.println(responseEntity.getHeaders().getContentType());
}
@Test
public void testPostMapJson() {
//请求地址
String url = "http://localhost/auth/testPostMap";
//String url = "http://localhost/auth/testPostJson";
// 请求头设置
HttpHeaders headers = new HttpHeaders();
//headers.setContentType(MediaType.APPLICATION_JSON); //提交json数据
headers.setContentType(MediaType.APPLICATION_JSON_UTF8); //提交json数据
// 提交json数据(map)
Map<String, String> map = new HashMap<>();
map.put("app_id", "cli_a615cbb9bf123456");
map.put("app_secret", "rjBwrcUIwuQoFnsFyixwqePHVabcdef");
// 组装请求体(指定第一个参数的泛型)
HttpEntity<Map<String, String>> request = new HttpEntity<>(map, headers);
// 提交json数据
//JSONObject jsonParam = new JSONObject();
//jsonParam.put("app_id", "cli_a615cbb9bf123456");
//jsonParam.put("app_secret", "rjBwrcUIwuQoFnsFyixwqePHVabcdef");
//HttpEntity<JSONObject> request = new HttpEntity<>(jsonParam, headers);
// postForObject发起请求
String str = restTemplate.postForObject(url, request, String.class);
System.out.println(str);
// postForEntity发起请求
// String.class指定返回的Body的类型
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, request, String.class);
//ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(url, request, JSONObject.class);
System.out.println(responseEntity.getStatusCode().value());
System.out.println(responseEntity.getBody());
System.out.println(responseEntity.getHeaders().getContentType());
}
}
也可以用exchange方法
3、接收Controller示例
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.Map;
/**
* 测试Controller
*/
@Controller
@RequestMapping("/auth")
@Slf4j
public class AuthController {
// http://localhost/auth/testPostForm
@RequestMapping("/testPostForm")
@ResponseBody
public String testPost1(@RequestParam(name = "param1") String param1, @RequestParam(name = "param2") String param2) {
log.info("param1:"+param1);
log.info("param2:"+param2);
return "OK";
}
@RequestMapping("/testPostMap")
@ResponseBody
public String testPost2(@RequestBody Map<String, Object> reqMap) {
String appId = (String)reqMap.get("app_id");
String appSecret = (String)reqMap.get("app_secret");
log.info("appId:"+appId);
log.info("appSecret:"+appSecret);
return "OK";
}
@RequestMapping("/testPostJson")
@ResponseBody
public JSONObject testPost3(@RequestBody JSONObject jsonObject) {
String appId = jsonObject.getString("app_id");
String appSecret = jsonObject.getString("app_secret");
log.info("appId:"+appId);
log.info("appSecret:"+appSecret);
JSONObject resp = new JSONObject();
resp.put("code", 0);
resp.put("msg", "");
return resp;
}
}