将API返回的图像保存为JSON

时间:2019-03-18 02:44:27

标签: java spring spring-boot jpeg httpresponse

我正在使用Meme generator API。我的目标是使用API​​生成模因,能够查看并将其另存为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,所以我改用了以下代码段:

  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();

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

的负载
  

ufffd

字符串中的

片段,这基本上意味着我正在尝试读取没有Unicode表示形式的代码。我已经看到了here的解决方案,该如何解决这个问题,但是我不确定自己的方法是否正确。

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

enter image description here

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

谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

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

尝试将响应从API直接保存到文件中,您会看到它是图像。

答案 1 :(得分:0)

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

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. 使用指定的filePath创建文件
  5. 将BufferedImage写入文件