如何使用 Android Studio 连接类中的两个端点

How to connect two endpoints in a class with Android Studio

提问人:Gui_Finkler 提问时间:6/20/2023 最后编辑:Brian Tompsett - 汤莱恩Gui_Finkler 更新时间:7/3/2023 访问量:40

问:

我想连接到一个 API 的两个端点。我正在使用 GEO 数据库 API 来访问国家/地区详细信息。我需要在国家/地区端点传递的 id。为此,我想动态地执行此操作,获取此 API 提供的代码并将此代码传递给另一个端点。在本例中,我对两者使用相同的模板。对不起,如果我说的话令人困惑,我迷路了。在这种情况下,国家/地区终端节点连接正常,而 id 为该 ID 的终端节点返回 null

终结点:geo/countries TO 终结点:geo/countries/{IdCountry}

类连接


public class Connection {

    private static final String BASE_URL = "https://wft-geo-db.p.rapidapi.com/v1/";
    private static final String API_KEY = "";
    private static final String API_HOST = "wft-geo-db.p.rapidapi.com";

    public static String connectHttp(String end_Point) {
        String return_api = null;
        String url_amount = BASE_URL + end_Point;
        System.out.println(url_amount);
        try {
            URL url = new URL(url_amount);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("X-RapidAPI-Key", API_KEY);
            connection.setRequestProperty("X-RapidAPI-Host", API_HOST);
            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                reader.close();
                return_api = stringBuilder.toString();
            }
            else
                System.out.println("Error, code of return: " + responseCode);

            connection.disconnect();
        }
        catch (Exception error) {
            error.printStackTrace();
        }
        return return_api;
    }
}

用于解析 json 的类


public class CountryFetcher {

    private Handler handler;
    private OnCountryFetchListener listener;

    public CountryFetcher(Handler handler, OnCountryFetchListener listener) {
        this.handler = handler;
        this.listener = listener;
    }

    public void fetchCountries() {
        HandlerThread handlerThread = new HandlerThread("CountryFetcherThread");
        handlerThread.start();

        Handler handler = new Handler(handlerThread.getLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                String result = Connection.connectHttp("geo/countries");

                if (result != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        JSONArray jsonArray = jsonObject.getJSONArray("data");

                        List<Country> countries = new ArrayList<>();

                        for (int i = 0; i < jsonArray.length(); i++) {
                            JSONObject countryJson = jsonArray.getJSONObject(i);
                            String code = countryJson.getString("code");
                            String name = countryJson.getString("name");
                            Country country = new Country(code, name);

                            String countryDetailsResult = Connection.connectHttp("geo/countries/" + country.getCode());

                            if (countryDetailsResult != null) {
                                try {
                                    JSONObject countryDetailsJson = new JSONObject(countryDetailsResult);
                                    JSONObject countryDataJson = countryDetailsJson.getJSONObject("data");


                                    String callingCode = countryDataJson.getString("callingCode");
                                    String flagImageUri = countryDataJson.getString("flagImageUri");
                                    int numRegions = countryDataJson.getInt("numRegions");
                                    String wikiDataId = countryDataJson.getString("wikiDataId");


                                    country.setCallingCode(callingCode);
                                    country.setFlagImageUri(flagImageUri);
                                    country.setNumRegions(numRegions);
                                    country.setWikiDataId(wikiDataId);

                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            countries.add(country);
                        }

                        if (listener != null) {
                            listener.CountryFetchSuccess(countries);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                        if (listener != null) {
                            listener.CountryFetchError();
                        }
                    }
                } else {
                    if (listener != null) {
                        listener.CountryFetchError();
                    }
                }
            }
        });
    }

    public interface OnCountryFetchListener {
        void CountryFetchSuccess(List<Country> countries);
        void CountryFetchError();
    }
}

国家模式


public class Country {

    private String code;
    private String name;
    private String callingCode;
    private String flagImageUri;
    private int numRegions;
    private String wikiDataId;

    public Country(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }

    public String getName() {
        return name;
    }

    public String getCallingCode() {
        return callingCode;
    }

    public void setCallingCode(String callingCode) {
        this.callingCode = callingCode;
    }

    public String getFlagImageUri() {
        return flagImageUri;
    }

    public void setFlagImageUri(String flagImageUri) {
        this.flagImageUri = flagImageUri;
    }

    public int getNumRegions() {
        return numRegions;
    }

    public void setNumRegions(int numRegions) {
        this.numRegions = numRegions;
    }

    public String getWikiDataId() {
        return wikiDataId;
    }

    public void setWikiDataId(String wikiDataId) {
        this.wikiDataId = wikiDataId;
    }
}

我不知道我是否应该将端点请求放在解析类的另一个循环中。

我尝试使用自己的循环创建单独的方法,类似于我对第一个端点所做的。但它也返回了 null。

我想知道如何修复此错误。

Java Android REST 语法错误

评论

0赞 Robert 6/20/2023
我根本看不出你在哪里使用模板。只是您手动将 JSON 对象转换为模型类。 恕我直言,您应该考虑从 JSON 自动解析模型,就像 Jackson 提供的那样。这将大大简化您的代码,只需模型类,并使用 Jackson 直接从响应数据 InputStream 中解析它。没有人真的想手动分析所有 JSON 数据结构。

答: 暂无答案