如何以编程方式调用GET API

时间:2018-03-26 22:01:28

标签: java spring rest spring-boot resttemplate

我创建了两个不同的Spring-boot微服务。服务“A”和服务“B”。服务A具有以下GET API,可让您通过其ID检索视频。

    @RestController
    public class VideoController {

    @Autowired
    VideoService videoService;

    @GetMapping(path = "videos/{videoId}", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    public StreamingResponseBody videoStream(@PathVariable String videoId)
            throws IOException {
        File videoFile = videoService.getVideoById(videoId);
        if (videoFile != null) {
            final InputStream videoFileStream = new FileInputStream(videoFile);
            return (os) -> {
                readAndWrite(videoFileStream, os);
            };
        } else {
            return null;
        }
    }

    private void readAndWrite(final InputStream is, OutputStream os) throws IOException {
        byte[] bytes = new byte[2048];
        int read = 0;
        while ((read = is.read(bytes)) > 0) {
            os.write(bytes, 0, read);
        }
        os.flush();
    }

}

服务B需要以编程方式调用上述API。

我使用Rest Template完成了它,代码如下。

public Object getVideo(String videoId) {
    RestTemplate restTemplate = new RestTemplate();
    String videoURL = videostoreURL + "/videos/" + videoId;

    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_OCTET_STREAM));

    //HttpEntity statusEntity = new HttpEntity(headers);

    Object videoFound = restTemplate.getForObject(videoURL, Object.class);

    return videoFound;
}

我创建了服务B的Rest控制器,也类似于服务A中的控制器。

当我调用服务B的控制器时,我在Postman中收到以下错误。

{
 "timestamp": 1522082255763,
 "status": 406,
 "error": "Not Acceptable",
 "exception": "org.springframework.web.HttpMediaTypeNotAcceptableException",
 "message": "Could not find acceptable representation",
 "path": "/serviceB/videos/sample.mp4"
} 

如何修复我的REST模板?

0 个答案:

没有答案