You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot中使用RestTemplate调用Graph API获取图片报错问题求助

解决RestTemplate调用Graph API获取用户头像的转换错误问题

我来帮你搞定这个问题!你遇到的报错本质是默认的RestTemplate没有配置能处理image/jpeg这类二进制图片数据的HttpMessageConverter,而你指定的响应类型是Object,框架找不到合适的转换器来解析返回的图片二进制流,所以抛出了这个错误。

下面给你两种可行的解决方案:

方案一:直接用字节数组接收响应(最简单直接)

既然接口返回的是二进制图片数据,直接用byte[]作为响应类型就可以了,修改你的调用代码:

final ResponseEntity<byte[]> profilePicture = restTemplate.exchange(graphUrl, HttpMethod.GET, new HttpEntity<>(header), byte[].class);

拿到byte[]之后,你可以把它转换成InputStream,或者直接写入文件,比如:

byte[] imageBytes = profilePicture.getBody();
if (imageBytes != null) {
    Files.write(Paths.get("user-avatar.jpg"), imageBytes);
}

方案二:给RestTemplate添加支持图片的消息转换器

如果你的项目需要频繁处理图片这类二进制响应,可以给RestTemplate配置ByteArrayHttpMessageConverter,并指定它支持的媒体类型。修改你的RestTemplate Bean定义:

import org.springframework.http.MediaType;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

@Bean
public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    ByteArrayHttpMessageConverter byteArrayConverter = new ByteArrayHttpMessageConverter();
    
    // 添加需要支持的图片媒体类型
    List<MediaType> supportedMediaTypes = new ArrayList<>();
    supportedMediaTypes.add(MediaType.IMAGE_JPEG);
    supportedMediaTypes.add(MediaType.IMAGE_PNG);
    supportedMediaTypes.add(MediaType.IMAGE_GIF);
    byteArrayConverter.setSupportedMediaTypes(supportedMediaTypes);
    
    restTemplate.getMessageConverters().add(byteArrayConverter);
    return restTemplate;
}

配置完成后,你再用byte[]作为响应类型调用接口,RestTemplate就能正确解析图片响应了。

补充说明:Postman能正常显示图片是因为它会自动识别二进制响应并渲染,而Spring的RestTemplate需要你明确指定响应类型或者配置对应的转换器来处理这类数据。

内容的提问来源于stack exchange,提问作者Aryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.27 15:37:42