Search in sources :

Example 46 with Builder

use of okhttp3.Request.Builder in project instructure-android by instructure.

the class RequestInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Request.Builder builder = request.newBuilder();
    final String token = ApiPrefs.getToken();
    final String userAgent = ApiPrefs.getUserAgent();
    final String domain = ApiPrefs.getFullDomain();
    /* Nearly all requests are instantiated using RestBuilder and will have been tagged with
        a RestParams instance. Here we will attempt to retrieve it, but if unsuccessful we will
        fall back to a new RestParams instance with default values. */
    RestParams params;
    if (request.tag() != null && request.tag() instanceof RestParams) {
        params = (RestParams) request.tag();
    } else {
        params = new RestParams.Builder().build();
    }
    // Set the UserAgent
    if (!userAgent.equals("")) {
        builder.addHeader("User-Agent", userAgent);
    }
    // Authenticate if possible
    if (!params.shouldIgnoreToken() && !token.equals("")) {
        builder.addHeader("Authorization", "Bearer " + token);
    }
    // Add Accept-Language header for a11y
    builder.addHeader("accept-language", getAcceptedLanguageString());
    if (!APIHelper.hasNetworkConnection() || params.isForceReadFromCache()) {
        // Offline or only want cached data
        builder.cacheControl(CacheControl.FORCE_CACHE);
    } else if (params.isForceReadFromNetwork()) {
        // Typical from a pull-to-refresh
        builder.cacheControl(CacheControl.FORCE_NETWORK);
    }
    // Fun Fact: HTTP referer (originally a misspelling of referrer) is an HTTP header field that identifies
    // the address of the webpage that linked to the resource being requested
    // Source: https://en.wikipedia.org/wiki/HTTP_referer
    // Institutions need the referrer for a variety of reasons - mostly for restricted content
    // Strip out non-ascii characters, otherwise addHeader may throw an exception
    builder.addHeader("Referer", domain.replaceAll("[^\\x20-\\x7e]", ""));
    request = builder.build();
    // Masquerade if necessary
    if (ApiPrefs.isMasquerading()) {
        HttpUrl url = request.url().newBuilder().addQueryParameter("as_user_id", Long.toString(ApiPrefs.getMasqueradeId())).build();
        request = request.newBuilder().url(url).build();
    }
    if (params.usePerPageQueryParam()) {
        HttpUrl url = request.url().newBuilder().addQueryParameter("per_page", Integer.toString(ApiPrefs.getPerPageCount())).build();
        request = request.newBuilder().url(url).build();
    }
    return chain.proceed(request);
}
Also used : RestParams(com.instructure.canvasapi2.builders.RestParams) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl)

Example 47 with Builder

use of okhttp3.Request.Builder in project brave by openzipkin.

the class TracingInterceptor method intercept.

@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request.Builder builder = chain.request().newBuilder();
    Span span = clientHandler.handleSend(injector, builder, chain.request());
    Response response = null;
    Throwable error = null;
    try (Tracer.SpanInScope ws = tracer.withSpanInScope(span)) {
        return response = chain.proceed(builder.build());
    } catch (IOException | RuntimeException | Error e) {
        error = e;
        throw e;
    } finally {
        clientHandler.handleReceive(response, error, span);
    }
}
Also used : Response(okhttp3.Response) Tracer(brave.Tracer) Request(okhttp3.Request) IOException(java.io.IOException) Span(brave.Span)

Example 48 with Builder

use of okhttp3.Request.Builder in project YhLibraryForAndroid by android-coco.

the class LoggerInterceptor method logForResponse.

private Response logForResponse(Response response, long duration) {
    try {
        // ===>response LogUtils
        LogUtils.e(tag, "============服务器回复'LogUtils============开始");
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        LogUtils.e(tag, "请求url : " + clone.request().url());
        LogUtils.e(tag, "请求code : " + clone.code());
        LogUtils.e(tag, "请求协议protocol : " + clone.protocol());
        if (!TextUtils.isEmpty(clone.message())) {
            LogUtils.e(tag, "是否成功 : " + clone.message());
            if (showResponse) {
                ResponseBody body = clone.body();
                if (body != null) {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null) {
                        LogUtils.e(tag, "响应主体的类型 : " + mediaType.toString());
                        if (isText(mediaType)) {
                            String resp = body.string();
                            LogUtils.e(tag, "响应主体的内容 : " + resp);
                            body = ResponseBody.create(mediaType, resp);
                            LogUtils.e(tag, "============服务器回复'LogUtils==========结束" + duration + "毫秒");
                            return response.newBuilder().body(body).build();
                        } else {
                            LogUtils.e(tag, "响应主体的内容 : " + " 也许[文件部分],太大了太大了,忽略了!");
                        }
                    }
                }
            }
        }
        LogUtils.e(tag, "============服务器回复'LogUtils==========结束" + duration + "毫秒");
    } catch (Exception e) {
        LogUtils.e(tag, "============服务器回复打印异常:" + e.getMessage());
    }
    return response;
}
Also used : Response(okhttp3.Response) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 49 with Builder

use of okhttp3.Request.Builder in project YhLibraryForAndroid by android-coco.

the class PostFormRequest method buildRequestBody.

@Override
protected RequestBody buildRequestBody() {
    if (files == null || files.isEmpty()) {
        FormBody.Builder builder = new FormBody.Builder();
        addParams(builder);
        FormBody formBody = builder.build();
        return formBody;
    } else {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        addParams(builder);
        for (int i = 0; i < files.size(); i++) {
            PostFormBuilder.FileInput fileInput = files.get(i);
            RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(fileInput.filename)), fileInput.file);
            builder.addFormDataPart(fileInput.key, fileInput.filename, fileBody);
        }
        return builder.build();
    }
}
Also used : MultipartBody(okhttp3.MultipartBody) PostFormBuilder(org.yh.library.okhttp.builder.PostFormBuilder) FormBody(okhttp3.FormBody) PostFormBuilder(org.yh.library.okhttp.builder.PostFormBuilder) RequestBody(okhttp3.RequestBody)

Example 50 with Builder

use of okhttp3.Request.Builder in project LabDayApp by jakdor.

the class AuthenticationInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();
    Request.Builder builder = original.newBuilder().header("Authorization", "token " + authToken);
    Request request = builder.build();
    return chain.proceed(request);
}
Also used : Request(okhttp3.Request)

Aggregations

Request (okhttp3.Request)170 Response (okhttp3.Response)120 OkHttpClient (okhttp3.OkHttpClient)103 IOException (java.io.IOException)89 RequestBody (okhttp3.RequestBody)68 Test (org.junit.Test)68 File (java.io.File)36 MultipartBody (okhttp3.MultipartBody)36 HttpUrl (okhttp3.HttpUrl)34 Map (java.util.Map)31 MockResponse (okhttp3.mockwebserver.MockResponse)31 Call (okhttp3.Call)26 Interceptor (okhttp3.Interceptor)26 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)26 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)24 Builder (okhttp3.OkHttpClient.Builder)21 Retrofit (retrofit2.Retrofit)21 Builder (okhttp3.Request.Builder)19 FormBody (okhttp3.FormBody)18 ResponseBody (okhttp3.ResponseBody)18