Search in sources :

Example 31 with MediaType

use of okhttp3.MediaType in project retrofit by square.

the class RequestBuilder method build.

Request build() {
    HttpUrl url;
    HttpUrl.Builder urlBuilder = this.urlBuilder;
    if (urlBuilder != null) {
        url = urlBuilder.build();
    } else {
        // No query parameters triggered builder creation, just combine the relative URL and base URL.
        // noinspection ConstantConditions Non-null if urlBuilder is null.
        url = baseUrl.resolve(relativeUrl);
        if (url == null) {
            throw new IllegalArgumentException("Malformed URL. Base: " + baseUrl + ", Relative: " + relativeUrl);
        }
    }
    RequestBody body = this.body;
    if (body == null) {
        // Try to pull from one of the builders.
        if (formBuilder != null) {
            body = formBuilder.build();
        } else if (multipartBuilder != null) {
            body = multipartBuilder.build();
        } else if (hasBody) {
            // Body is absent, make an empty body.
            body = RequestBody.create(null, new byte[0]);
        }
    }
    MediaType contentType = this.contentType;
    if (contentType != null) {
        if (body != null) {
            body = new ContentTypeOverridingRequestBody(body, contentType);
        } else {
            requestBuilder.addHeader("Content-Type", contentType.toString());
        }
    }
    return requestBuilder.url(url).method(method, body).build();
}
Also used : MediaType(okhttp3.MediaType) HttpUrl(okhttp3.HttpUrl) RequestBody(okhttp3.RequestBody)

Example 32 with MediaType

use of okhttp3.MediaType in project MVPFrames by RockyQu.

the class TokenInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    // try the request
    Response originalResponse = chain.proceed(request);
    /**
     * 通过如下方法提前获取到请求完成的数据
     */
    ResponseBody responseBody = originalResponse.body();
    BufferedSource source = responseBody.source();
    // Buffer the entire body.
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    Charset charset = UTF8;
    MediaType contentType = responseBody.contentType();
    if (contentType != null) {
        charset = contentType.charset(UTF8);
    }
    String bodyString = buffer.clone().readString(charset);
    Log.e("body---------->", bodyString);
    // otherwise just pass the original response on
    return originalResponse;
}
Also used : Response(okhttp3.Response) Buffer(okio.Buffer) Request(okhttp3.Request) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 33 with MediaType

use of okhttp3.MediaType in project MVPFrames by RockyQu.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Level level = this.level;
    Request request = chain.request();
    if (level == Level.NONE) {
        return chain.proceed(request);
    }
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    // 请求地址
    Connection connection = chain.connection();
    Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
    String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
    if (hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    log(requestStartMessage);
    // Content-Type
    if (hasRequestBody) {
        if (requestBody.contentType() != null) {
            log("Content-Type: " + requestBody.contentType());
        }
        if (requestBody.contentLength() != -1) {
            log("Content-Length: " + requestBody.contentLength());
        }
    }
    // 拼装请求参数
    Headers headers = request.headers();
    for (int i = 0, count = headers.size(); i < count; i++) {
        String name = headers.name(i);
        if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
            log(name + ": " + headers.value(i));
        }
    }
    // Request结束
    if (!hasRequestBody) {
        log("--> END " + request.method());
    } else if (bodyEncoded(request.headers())) {
        log("--> END " + request.method() + " (encoded body omitted)");
    } else {
        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        if (isPlaintext(buffer)) {
            log(buffer.readString(charset));
            log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        } else {
            log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
        }
    }
    // Response开始
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        log("<-- HTTP FAILED: " + e);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    long contentLength = responseBody.contentLength();
    String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
    log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (", " + bodySize + " body") + ')');
    headers = response.headers();
    for (int i = 0, count = headers.size(); i < count; i++) {
        log(headers.name(i) + ": " + headers.value(i));
    }
    if (!HttpHeaders.hasBody(response)) {
        log("<-- END HTTP");
    } else if (bodyEncoded(response.headers())) {
        log("<-- END HTTP (encoded body omitted)");
    } else {
        BufferedSource source = responseBody.source();
        // Buffer the entire body.
        source.request(Long.MAX_VALUE);
        Buffer buffer = source.buffer();
        Charset charset = UTF8;
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                log("Couldn't decode the response body; charset is likely malformed.");
                log("<-- END HTTP");
                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
            return response;
        }
        if (contentLength != 0) {
            log(buffer.clone().readString(charset));
        }
        log("<-- END HTTP (" + buffer.size() + "-byte body)");
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 34 with MediaType

use of okhttp3.MediaType in project MVPFrames by RockyQu.

the class NetworkInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    // 在请求服务器之前可以拿到request,做一些操作比如给request添加header,如果不需要操作则返回参数中的request
    if (handler != null) {
        request = handler.onHttpRequest(chain, request);
    }
    NetworkStatusReceiver.Type type = NetworkStatusReceiver.getType(application);
    if (type == NetworkStatusReceiver.Type.NONE) {
        // 无网络时强制从缓存读取(必须得写,不然断网状态下,退出应用,或者等待一分钟后,会获取不到缓存)
        request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
    }
    Response originalResponse = chain.proceed(request);
    if (type == NetworkStatusReceiver.Type.MOBILE || type == NetworkStatusReceiver.Type.WIFI) {
        // 0秒
        int maxAge = 0;
        originalResponse = originalResponse.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "public, max-age=" + maxAge).build();
    } else {
        // 1小时
        int maxTime = 60 * 60;
        originalResponse = originalResponse.newBuilder().removeHeader("Pragma").removeHeader("Cache-Control").header("Cache-Control", "public, only-if-cached, max-stale=" + maxTime).build();
    }
    // 读取服务器返回的结果
    ResponseBody responseBody = originalResponse.body();
    BufferedSource source = responseBody.source();
    // Buffer the entire body.
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    // 获取content的压缩类型
    String encoding = originalResponse.headers().get("Content-Encoding");
    Buffer clone = buffer.clone();
    String bodyString;
    // 解析response content
    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        // content使用gzip压缩
        bodyString = ZipUtils.decompressForGzip(clone.readByteArray());
    } else if (encoding != null && encoding.equalsIgnoreCase("zlib")) {
        // content使用zlib压缩
        bodyString = ZipUtils.decompressToStringForZlib(clone.readByteArray());
    } else {
        // content没有被压缩
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = responseBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(charset);
        }
        bodyString = clone.readString(charset);
    }
    // 这里可以提前一步拿到服务器返回的结果,外部实现此接口可以做一些操作,比如Token超时,重新获取
    if (handler != null) {
        return handler.onHttpResponse(bodyString, chain, request, originalResponse);
    }
    return originalResponse;
}
Also used : Response(okhttp3.Response) Buffer(okio.Buffer) Request(okhttp3.Request) NetworkStatusReceiver(com.tool.common.http.receiver.NetworkStatusReceiver) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 35 with MediaType

use of okhttp3.MediaType in project AndoridLib by twp520.

the class HttpLogInterceptor method logForRequest.

private void logForRequest(Request request) {
    try {
        String url = request.url().toString();
        Log.e(tag, "========请求日志开始=======");
        Log.e(tag, "请求方式 : " + request.method());
        Log.e(tag, "url : " + url);
        RequestBody requestBody = request.body();
        if (requestBody != null) {
            MediaType mediaType = requestBody.contentType();
            if (mediaType != null) {
                Log.e(tag, "请求内容类别 : " + mediaType.toString());
                if (isText(mediaType)) {
                    Log.e(tag, "请求内容 : " + bodyToString(request));
                } else {
                    Log.e(tag, "请求内容 : " + " 无法识别。");
                }
            }
        }
        Log.e(tag, "========请求日志结束=======");
    } catch (Exception e) {
    // e.printStackTrace();
    }
}
Also used : MediaType(okhttp3.MediaType) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Aggregations

MediaType (okhttp3.MediaType)99 RequestBody (okhttp3.RequestBody)86 Request (okhttp3.Request)82 Response (okhttp3.Response)74 IOException (java.io.IOException)67 ResponseBody (okhttp3.ResponseBody)35 Buffer (okio.Buffer)30 BufferedSink (okio.BufferedSink)28 Charset (java.nio.charset.Charset)25 Headers (okhttp3.Headers)19 BufferedSource (okio.BufferedSource)19 Map (java.util.Map)17 OkHttpClient (okhttp3.OkHttpClient)15 HashMap (java.util.HashMap)12 InputStream (java.io.InputStream)11 MultipartBody (okhttp3.MultipartBody)11 MockResponse (okhttp3.mockwebserver.MockResponse)11 EOFException (java.io.EOFException)10 List (java.util.List)9 Connection (okhttp3.Connection)9