我是 Java spring 框架的新手, 我需要一种从我的应用程序调用外部 Rest Api 的方法。 是否有任何“最佳实践”http 客户端可以满足我的需要?
提前致谢
最佳答案
使用 RestTemplate:
@RestController
public class SampleController {
@Autowired
RestTemplate restTemplate;
@RequestMapping(value = "/sample/endpoint", method = RequestMethod.POST)
public String createProducts(@RequestBody SampleClass sampleClass) {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<SampleClass> entity = new HttpEntity<SampleClass>(sampleClass,headers);
return restTemplate.exchange(
"https://example.com/endpoint", HttpMethod.POST, entity, String.class).getBody();
}
}
关于java - 如何向外部 Rest Api 发出 Http Post 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54665828/