简体   繁体   English

我怎样才能从一个 REST API 中得到具体的数据?

[英]How can I get specific data from a REST API in?

So I'm trying to access data frim a rest api using java code and I'm not very experienced in getting data from an api using java. I had found the code below on another question.因此,我正在尝试使用 java 代码从 rest api 访问数据,而我在使用 java 从 api 获取数据方面不是很有经验。我在另一个问题上找到了下面的代码。 This code was able to output all the data from the link but I'm a bit confused on how to get specific values from the link.此代码能够 output 来自链接的所有数据,但我对如何从链接获取特定值感到有点困惑。 The link in the code below shows the nutrition info for an apple and what I'm looking for is being able to output specific values such as the fdcId or the description.下面代码中的链接显示了苹果的营养信息,我正在寻找的是能够 output 特定值,例如 fdcId 或描述。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
    public static void main(String[] args) {
        try {

            URL url = new URL("https://api.nal.usda.gov/fdc/v1/food/1750339?api_key=DEMO_KEY");//your url i.e fetch data from .
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");
            if (conn.getResponseCode() != 200) {
                throw new RuntimeException("Failed : HTTP Error code : "
                        + conn.getResponseCode());
            }
            InputStreamReader in = new InputStreamReader(conn.getInputStream());
            BufferedReader br = new BufferedReader(in);
            String output;
            while ((output = br.readLine()) != null) {
                System.out.println(output);
            }
            conn.disconnect();

        } catch (Exception e) {
            System.out.println("Exception in NetClientGet:- " + e);
        }
    }
}

I haven't really tried much with the code.我并没有真正尝试过代码。 I tried looking for the answer for this online and didn't find much我试着在网上寻找这个问题的答案,但没有找到太多

You need to look how to parse Json in Java. This way you can take any data you need from that Json file.您需要查看如何在 Java 中解析 Json。这样您就可以从该 Json 文件中获取所需的任何数据。 Some explanations for the similar question are here. 类似问题的一些解释在这里。

Usually Spring or other frameworks used for this purposes.通常是 Spring 或用于此目的的其他框架。 In your example you can save JSON response to string like this:在您的示例中,您可以像这样保存 JSON 对字符串的响应:

String reponse = "";
String line;
while ((line = br.readLine()) != null) {
    reponse += line;
}

And than parse this JSON, fe using Jackson ObjectMapper convert it into your dto.而不是解析这个 JSON,fe 使用 Jackson ObjectMapper 将它转换成你的 dto。
There is an example here: https://www.baeldung.com/jackson-object-mapper-tutorial这里有一个例子: https://www.baeldung.com/jackson-object-mapper-tutorial

Your question should be divided in two parts:你的问题应该分为两部分:

  1. How to read info from API如何从 API 读取信息
  2. How to parse it.如何解析它。

The first part you already did.您已经完成的第一部分。 But you can do it with less code by far.但是到目前为止,您可以用更少的代码来完成。 You can use 3d party HTTP clients.可以使用3d方HTTP客户端。 The most popular are Apache Http Client with good tutorial - Apache HttpClient Tutorial and OK Http client with good tutorial - A Guide to OkHttp .最受欢迎的是Apache Http具有良好教程的客户端 - Apache HttpClient 教程OK Http具有良好教程的客户端 - OkHttp指南 However, I wrote my own Http client that is not widely known but very simple to use.但是,我编写了自己的 Http 客户端,该客户端并不广为人知,但使用起来非常简单。

The second part is how to parse Json. And for that you can use also 3d party Json parsers.第二部分是如何解析 Json。为此,您还可以使用 3d 方 Json 解析器。 The most popular ones would be Json Jackson or Gson (of Google).最受欢迎的是Json JacksonGson (Google 的)。 And again I also wrote my own thin wrapper over Json-Jackson that allows you to parse Json very simply.同样,我还在 Json-Jackson 上编写了自己的瘦包装器,它允许您非常简单地解析 Json。 Here is the code example that uses my own utilities:这是使用我自己的实用程序的代码示例:

HttpClient httpClient = new HttpClient();
try {
    httpClient.setConnectionUrl("https://api.nal.usda.gov/fdc/v1/food/1750339?api_key=DEMO_KEY");
    httpClient.setRequestHeader("Accept", "application/json");
    String jsonResponse = httpClient.sendHttpRequest(HttpClient.HttpMethod.GET);
    Map<String, Object> map = JsonUtils.readObjectFromJsonString(jsonResponse, Map.class);
    System.out.println("fdcid: " + map.get("fdcId"));
    System.out.println("description: " + map.get("description"));
} catch (Exception e) {
    System.out.println(httpClient.getLastResponseCode() + " "
            + httpClient.getLastResponseMessage() + TextUtils.getStacktrace(e, false));
}

If you run this code this would be the output:如果您运行此代码,这将是 output:

fdcid: 1750339
description: Apples, red delicious, with skin, raw

The classes HttpClient , JsonUtils and TextUtils all come as part of MgntUtils Open Source library written and maintained by me. HttpClientJsonUtilsTextUtils类都是我编写和维护的 MgntUtils 开源库的一部分。 Here is Javadoc for the library If you want the source code of the whole library you can get it on Github here , and just the library as Maven artifact is available from Maven Central here这是库的Javadoc如果你想要整个库的源代码,你可以在这里的 Github 上获得它,而作为 Maven 工件的库可以从 Maven Central here获得

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM