【问题标题】:Saving an image returned by an API in JSON以 JSON 格式保存 API 返回的图像
【发布时间】:2019-03-18 02:44:26
【问题描述】:

我正在使用Meme generator API。我的目标是使用 API 生成 meme,能够查看并保存为 JPG 图片。

当我尝试使用创建者提供的 Java 代码时,我收到一条错误消息。

下面是提供的失败代码:

  HttpResponse<JsonNode> response = Unirest.get("https://ronreiter-meme-generator.p.rapidapi.com/meme?font=Impact&font_size=50&meme=Condescending-Wonka&top=Yolo&bottom=HA")
      .header("X-RapidAPI-Key", "TOP_SECRET")
      .asJson();

错误信息:

org.springframework.beans.factory.UnsatisfiedDependencyException: 创建文件中定义的名称为“APIController”的 bean 时出错 [C:\yaml\out\production\classes\com\example\demo\controllers\APIController.class]: 通过构造函数参数 0 表示的不满足的依赖关系; 嵌套异常是 org.springframework.beans.factory.BeanCreationException:错误 创建文件中定义的名称为“APIService”的bean [C:\yaml\out\production\classes\com\example\demo\services\APIService.class]: bean 实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException:失败 实例化 [com.example.demo.services.APIService]:构造函数抛出 例外;嵌套异常是 com.mashape.unirest.http.exceptions.UnirestException: java.lang.RuntimeException: java.lang.RuntimeException: org.json.JSONException:JSONArray 文本必须以 '[' 开头,位于 1 [字符 2 第 1 行]

它说的是领域

response

无法解析为 JSONArray,所以我尝试了以下代码 sn-p:

  HttpResponse<String> meme = Unirest.get("https://ronreiter-meme-generator.p.rapidapi.com/meme?font=Impact&font_size=50&meme=Impossibru-Guy-Original&top=Random+meme&bottom=Bottom+text")
      .header("X-RapidAPI-Key", "TOP_SECRET")
      .asString();

在这种情况下,代码运行,但是当我调用端点时,我得到了很多

sn-ps 在字符串中,这基本上意味着我正在尝试读取在 Unicode 中没有表示的代码。我已经看到了here 的解决方案,我该如何处理这个问题,但我不太确定我是否走在正确的道路上。

根据提供 API 的网站,我应该得到这样的响应:

您能给我一些如何解决这个问题的建议吗?

提前感谢您的帮助。

【问题讨论】:

  • 建议:问问自己为什么要以字符串或 json 格式返回 jpeg 图像?返回 jpg 的最简单方法是作为 jpeg,只需将原始 jpg 写入文件或输出流或您想要发送的任何位置。您可以使用 Base64 编码将 jpeg 转换为 json,但浏览器客户端将不知道如何显示它。所以通常最好将其保存并作为图像返回。

标签: java spring spring-boot jpeg httpresponse


【解决方案1】:

最终我可以在一些帮助下解决问题。 这里是:

HttpResponse httpResponse = Unirest.get("https://ronreiter-meme-generator.p.rapidapi.com/meme?font=Impact&font_size=50&meme=Condescending-Wonka&top=Top+text&bottom=Bottom+text")
        .header("X-RapidAPI-Key", "YOUR_SECRET_API_KEY")
        .asBinary();
InputStream inputStream = httpResponse.getRawBody();
BufferedImage imBuff = ImageIO.read(inputStream);
String filePath = "C:/x/x.jpg";
File file = new File(filePath);
ImageIO.write(imBuff, "jpg", file);

所以这里有几点要做:

  1. 以二进制数据形式检索响应
  2. 将其转换为 InputStream
  3. 从中创建一个 BufferedImage
  4. 使用指定的文件路径创建文件
  5. 将 BufferedImage 写入文件

【讨论】:

    【解决方案2】:

    您的 API 规范的内容类型包含“image/jpeg”。 这意味着响应中不包含 JSON,而是二进制图像数据,因此尝试将其解析为 JSON 会导致失败。

    尝试将 API 中的响应直接保存到文件中,您会看到它是一张图片。

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 2021-12-20
      • 2017-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      相关资源
      最近更新 更多