// 案例
@Controller
@RequestMapping("api")
public class Api {
@Autowired
private RestTemplate restTemplate;
@GetMapping("login")
public Object login(@RequestParam("username")String username, @RequestParam("password")String password) {
MultiValueMap<String, String> map = new LinkedMultiValueMap<>(1);
map.add("username",username);
map.add("password",password);
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8081/login?username={username}&password={password}", String.class,map);
String value = entity.getBody();
System.out.println("value = " + value);
return value;
}
}
@RequestMapping("login")
@RestController
public class LoginController {
@GetMapping
public Object login(@RequestParam("username")String username,@RequestParam("password")String password) {
// TODO login
System.out.println("username = " + username);
System.out.println("password = " + password);
return username + password;
}
}
@Configuration
public class RestTemplateConfig {
@Value("${restTemplate.connectTimeOut:15000}")
private int connectTimeOut;
@Value("${restTemplate.readTimeOut:5000}")
private int readTimeOut;
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
HttpMessageConverter<?> converterTarget = null;
HttpMessageConverter<?> jacksonConver = null;
for (HttpMessageConverter<?> item : converterList) {
if (item.getClass() == StringHttpMessageConverter.class) {
converterTarget = item;
break;
}
}
for (HttpMessageConverter<?> item : converterList) {
if (item.getClass() == MappingJackson2HttpMessageConverter.class) {
jacksonConver = item;
}
}
if (converterTarget != null) {
converterList.remove(converterTarget);
}
if (jacksonConver != null) {
converterList.remove(jacksonConver);
}
HttpMessageConverter<?> converter = new StringHttpMessageConverter(StandardCharsets.UTF_8);
HttpMessageConverter<?> jacksonConverter = new MyJacksonConvert(new ObjectMapper());
converterList.add(converter);
converterList.add(jacksonConverter);
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setConnectTimeout(connectTimeOut);
factory.setReadTimeout(readTimeOut);
return factory;
}
}
class MyJacksonConvert extends MappingJackson2HttpMessageConverter {
public MyJacksonConvert(ObjectMapper objectMapper) {
super(objectMapper);
// 驼峰式(AaBbCc)
// PropertyNamingStrategy.LOWER_CAMEL_CASE;
// 下划线连接单词 (aa_bb_cc,大小写不分)
// PropertyNamingStrategy.SNAKE_CASE;
// 驼峰式(AaBbCc)
// PropertyNamingStrategy.UPPER_CAMEL_CASE;
// 短横线连接单词(aa-bb-cc)
// PropertyNamingStrategy.KEBAB_CASE;
// 无论什么格式,转换成小写输出
// PropertyNamingStrategy.LOWER_CASE;
// 设置命名策略
this.objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE);
}
}