Использование токена API в моем приложении для Android

У меня есть токен api для моего api, но я не знаю, как реализовать его в моем коде ... это код, который у меня есть для достижения моего api:

public class DataVoetbalWebservice extends AsyncTask<VoetbalDataInterface, Void, JSONArray> {
    private static final int CONNECTION_TIMEOUT = 12000;
    private static final int DATARETRIEVAL_TIMEOUT = 12000;
    VoetbalDataInterface listener;
    private ProgressDialog dialog;
    Context context;

    public void setActivity(Context context) {
        this.context = context;
        dialog = new ProgressDialog(context);
    }
    @Override
    protected void onPreExecute() {
        dialog.setMessage("De Verschillende competities ophalen, even geduld aub.");
        dialog.show();
    }
    @Override
    protected JSONArray doInBackground(VoetbalDataInterface... params) {
        listener = params[0];

        // execute search
        disableConnectionReuseIfNecessary();

        HttpURLConnection urlConnection = null;
        try {
            // create connection
            //URL urlToRequest = new URL("http://datatank.stad.gent/4/bevolking/geboortes.json?%2Fbevolking%2Fgeboortes = ");
            URL urlToRequest = new URL("http://api.football-data.org/v1/competitions");
            urlConnection = (HttpURLConnection)
                    urlToRequest.openConnection();
            urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
            urlConnection.setReadTimeout(DATARETRIEVAL_TIMEOUT);

            // handle issues
            int statusCode = urlConnection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            } else if (statusCode != HttpURLConnection.HTTP_OK) {
                // handle any other errors, like 404, 500,..
            }

            // create JSON object from content
            InputStream in = new BufferedInputStream(
                    urlConnection.getInputStream());
            return new JSONArray(getResponseText(in));

        } catch (MalformedURLException e) {
            // URL is invalid
            Log.d("Info", e.getMessage());
        } catch (SocketTimeoutException e) {
            // data retrieval or connection timed out
            Log.d("Info", e.getMessage());
        } catch (IOException e) {
            // could not read response body
            // (could not create input stream)
            Log.d("Info", e.getMessage());
        } catch (JSONException e) {
            // response body is no valid JSON string
            Log.d("Info", e.getMessage());
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }

        return null;
    }


    @Override
    protected void onPostExecute(JSONArray json) {
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        ArrayList <Competitie> competities = new ArrayList<>();
            try {
                for (int i = 0; i < json.length(); i++) {
                    Competitie competitie = new Competitie();
                    JSONObject jsonObject = json.getJSONObject(i);
                    competitie.setId(jsonObject.getInt("id"));
                    competitie.setCaption(jsonObject.getString("caption"));
                    competitie.setLeague(jsonObject.getString("league"));
                    competitie.setYear(jsonObject.getString("year"));
                    competitie.setCurrentMatchday(jsonObject.getInt("currentMatchday"));
                    competitie.setNumberOfMatchdays(jsonObject.getInt("numberOfMatchdays"));
                    competitie.setNumberOfTeams(jsonObject.getInt("numberOfTeams"));
                    competitie.setNumberOfGames(jsonObject.getInt("numberOfGames"));
                    JSONObject links = jsonObject.getJSONObject("_links");
                    JSONObject teams = links.getJSONObject("teams");
                    JSONObject stand = links.getJSONObject("leagueTable");
                    competitie.setTeamString(teams.getString("href"));
                    competitie.setStandUrl(stand.getString("href"));

                    competities.add(competitie);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        listener.updateScreenCompetities(competities);

    }
    /**
     * required in order to prevent issues in earlier Android version.
     */
    private static void disableConnectionReuseIfNecessary() {
        // see HttpURLConnection API doc
        if (Integer.parseInt(Build.VERSION.SDK)
                < Build.VERSION_CODES.FROYO) {
            System.setProperty("http.keepAlive", "false");
        }
    }

    private static String getResponseText(InputStream inStream) {
        // very nice trick from
        // http://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner_1.html
        return new Scanner(inStream).useDelimiter("\\A").next();
    }

}

куда мне добавить токен, чтобы я мог связаться с API? .. потому что я не могу больше читать данные, потому что емкость запроса заполнена. Я уже получил свой токен API по электронной почте.

Это документация по api, как мне добавить заголовок запроса?
Документация об использовании токена

заранее спасибо

РЕДАКТИРОВАТЬ добавил эту строку кода, и теперь она работает!

urlConnection.setRequestProperty("X-Auth-Token","6a0c52afadac44f5bc65bd0dcfb363c2");

Это зависит от API. Они не дали вам никаких инструкций, как его использовать?

Sami Kuhmonen 02.06.2018 16:59

@SamiKuhmonen я добавил документацию к своему вопросу

Jelle de Keukeleire 02.06.2018 17:05
0
2
30
0

Другие вопросы по теме