如何将我的 api 密钥与加载程序一起使用?

How to use my api key with a loader?

我已经有一个为 api 使用加载程序的应用程序,但我想为新的 api 调整它。问题是新的 api 以这种格式提供给我:

curl -H "Authorization: Token <myToken>" "https://localelections.usvotefoundation.org/api/v1/states"

我可以在终端中很好地使用它,但我不知道如何在 Android Studio 中使用它。谁能指出我正确的方向?

我的 Utils 文件中的一些代码:

// Returns new URL object from the given string URL.
private static URL createUrl(String stringUrl) {
    URL url = null;
    try {
        url = new URL(stringUrl);
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Problem building the URL ", e);
    }
    return url;
}

//Make an HTTP request to the given URL and return a String as the response.
private static String makeHttpRequest(URL url) throws IOException {
    String jsonResponse = "";

    // If the URL is null, then return early.
    if (url == null) {
        return jsonResponse;
    }

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setReadTimeout(10000 /* milliseconds */);
        urlConnection.setConnectTimeout(15000 /* milliseconds */);
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        // If the request was successful (response code 200),
        // then read the input stream and parse the response.
        if (urlConnection.getResponseCode() == 200) {
            inputStream = urlConnection.getInputStream();
            jsonResponse = readFromStream(inputStream);
        } else {
            Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
        }
    } catch (IOException e) {
        Log.e(LOG_TAG, "Problem retrieving the JSON results.", e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (inputStream != null) {
            // Closing the input stream could throw an IOException, which is why
            // the makeHttpRequest(URL url) method signature specifies than an IOException
            // could be thrown.
            inputStream.close();
        }
    }
    return jsonResponse;
}

您需要像这样使用 HttpURLConnectionAuthorization 设置为页眉。

urlConnection.setRequestProperty ("Authorization", yourTokenHere);