Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding auth token as header to okhttp

I have the method below for making GET calls. I need to add a header to it, so as to pass the userToken to the server through the header. How do I do that?

public static String getJsonStringFromHttpGet(String url) {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder()
            .url(url)
            .build();
    try {
        Response responses = client.newCall(request).execute();
        return responses.body().string();
    } catch (IOException e) {
        Timber.e(e, "response exception:");
        return null;
    }
}
like image 925
Nouvel Travay Avatar asked Jul 08 '26 23:07

Nouvel Travay


1 Answers

Like this:

...
Request request = new Request.Builder()
        .url(url)
        .header("Authorization", userToken)
        .build();
...

Reference: https://github.com/square/okhttp/wiki/Recipes

like image 73
muratgu Avatar answered Jul 11 '26 12:07

muratgu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!