Java项目之间接口调用方式
一、服务提供接口
@RestController
@RequestMapping("/")
public class TransferController {
@Value("${server.port}")
private String serverPort;
@Resource
private TransferService transferService;
@GetMapping(value = "test")
public CommonResult test() {
return new CommonResult(200, "校验通过,serverPort: " + serverPort);
}
@PostMapping(value = "transfer")
public CommonResult transfer(@RequestParam(name = "content") String content) {
YlContent ylContent = YlContent.builder().content(content).build();
transferService.save(ylContent);
return new CommonResult(200, "成功,serverPort: " + serverPort, ylContent);
}
@PostMapping(value = "transfer2")
public CommonResult transfer2(@RequestBody YlContent ylContent) {
transferService.save(ylContent);
return new CommonResult(200, "成功,serverPort: " + serverPort, ylContent);
}
}
二、消费调用方
1.通过RestTemplate调用,传参测试为拼接数据
/**
* 测试
*/
@GetMapping("/consumer/transfer")
public CommonResult<Payment> transfer(){
HttpHeaders headers = new HttpHeaders();
RestTemplate template =new RestTemplate();
headers.add("Content-Type", "application/json;charset=UTF-8");
headers.add("Accept", "application/json");//请求头
headers.add("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbHBzLWpkLWFnZW50X3lsIiwidXNlck5hbWUiOiJjbHBzLWpkLWFnZW50IiwiaWF0IjoxNjI5Nzk4MTQyfQ.yickp5DLNR4c-OU7KLTpvj7rjySLtv8HlPRnn-ZVlyk");//请求头
String content = "测试asdfsafas";
HttpEntity requestEntity = new HttpEntity(content);
return restTemplate.postForObject("http://localhost:9001/transfer?content="+content,requestEntity, CommonResult.class);
}
2.通过RestTemplate调用,传参格式为Json字符串。
/**
* 测试
*/
@GetMapping("/consumer/transfer")
public CommonResult<Payment> transfer(){
HttpHeaders headers = new HttpHeaders();
RestTemplate template =new RestTemplate();
headers.add("Content-Type", "application/json;charset=UTF-8");
headers.add("Accept", "application/json");//请求头
headers.add("token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJjbHBzLWpkLWFnZW50X3lsIiwidXNlck5hbWUiOiJjbHBzLWpkLWFnZW50IiwiaWF0IjoxNjI5Nzk4MTQyfQ.yickp5DLNR4c-OU7KLTpvj7rjySLtv8HlPRnn-ZVlyk");//请求头
MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();
postParameters.add("content", "30001821");
HttpEntity requestEntity = new HttpEntity(
data, headers);
return restTemplate.postForObject("http://localhost:9001/transfer2",requestEntity, CommonResult.class);
}
3.通过HttpClient方式调用,略。