将auth令牌作为标头添加到okhttp

时间:2016-02-24 02:32:01

标签: android http-headers okhttp

我有以下方法进行GET调用。我需要添加一个标头,以便通过标头将userToken传递给服务器。我该怎么做?

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;
    }
}

1 个答案:

答案 0 :(得分:3)

像这样:

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

参考:https://github.com/square/okhttp/wiki/Recipes