Search in sources :

Example 86 with MediaType

use of okhttp3.MediaType in project android-client by GenesisVision.

the class OAuthOkHttpClient method execute.

public <T extends OAuthClientResponse> T execute(OAuthClientRequest request, Map<String, String> headers, String requestMethod, Class<T> responseClass) throws OAuthSystemException, OAuthProblemException {
    MediaType mediaType = MediaType.parse("application/json");
    Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri());
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            if (entry.getKey().equalsIgnoreCase("Content-Type")) {
                mediaType = MediaType.parse(entry.getValue());
            } else {
                requestBuilder.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null;
    requestBuilder.method(requestMethod, body);
    try {
        Response response = client.newCall(requestBuilder.build()).execute();
        return OAuthClientResponseFactory.createCustomResponse(response.body().string(), response.body().contentType().toString(), response.code(), response.headers().toMultimap(), responseClass);
    } catch (IOException e) {
        throw new OAuthSystemException(e);
    }
}
Also used : OAuthClientResponse(org.apache.oltu.oauth2.client.response.OAuthClientResponse) Response(okhttp3.Response) OAuthSystemException(org.apache.oltu.oauth2.common.exception.OAuthSystemException) Request(okhttp3.Request) OAuthClientRequest(org.apache.oltu.oauth2.client.request.OAuthClientRequest) MediaType(okhttp3.MediaType) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 87 with MediaType

use of okhttp3.MediaType in project xDrip by NightscoutFoundation.

the class GzipRequestInterceptor method gzip.

private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            // We don't know the compressed length in advance!
            return -1;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
Also used : GzipSink(okio.GzipSink) BufferedSink(okio.BufferedSink) RequestBody(okhttp3.RequestBody)

Example 88 with MediaType

use of okhttp3.MediaType in project MLib by DaoBillTang.

the class LoggerInterceptor method logForResponse.

private Response logForResponse(Response response) {
    try {
        // ===>response log
        Log.e(tag, "========response'log=======");
        Response.Builder builder = response.newBuilder();
        Response clone = builder.build();
        Log.e(tag, "url : " + clone.request().url());
        Log.e(tag, "code : " + clone.code());
        Log.e(tag, "protocol : " + clone.protocol());
        if (!TextUtils.isEmpty(clone.message())) {
            Log.e(tag, "message : " + clone.message());
        }
        if (showResponse) {
            ResponseBody body = clone.body();
            if (body != null) {
                MediaType mediaType = body.contentType();
                if (mediaType != null) {
                    Log.e(tag, "responseBody's contentType : " + mediaType.toString());
                    if (isText(mediaType)) {
                        String resp = body.string();
                        Log.e(tag, "responseBody's content : " + resp);
                        body = ResponseBody.create(mediaType, resp);
                        return response.newBuilder().body(body).build();
                    } else {
                        Log.e(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
                    }
                }
            }
        }
        Log.e(tag, "========response'log=======end");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}
Also used : Response(okhttp3.Response) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 89 with MediaType

use of okhttp3.MediaType in project xDrip-plus by jamorham.

the class GzipRequestInterceptor method gzip.

private RequestBody gzip(final RequestBody body) {
    return new RequestBody() {

        @Override
        public MediaType contentType() {
            return body.contentType();
        }

        @Override
        public long contentLength() {
            // We don't know the compressed length in advance!
            return -1;
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            BufferedSink gzipSink = Okio.buffer(new GzipSink(sink));
            body.writeTo(gzipSink);
            gzipSink.close();
        }
    };
}
Also used : GzipSink(okio.GzipSink) BufferedSink(okio.BufferedSink) RequestBody(okhttp3.RequestBody)

Example 90 with MediaType

use of okhttp3.MediaType in project autorest-clientruntime-for-java by Azure.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    // get logger
    Request request = chain.request();
    String context = request.header(LOGGING_HEADER);
    String bodyLoggingHeader = request.header(BODY_LOGGING);
    boolean bodyLogging = bodyLoggingHeader == null || Boolean.parseBoolean(bodyLoggingHeader);
    if (context == null) {
        context = "";
    }
    Logger logger = LoggerFactory.getLogger(context);
    // log URL
    if (logLevel != LogLevel.NONE) {
        log(logger, String.format("--> %s %s", request.method(), request.url()));
    }
    // log headers
    if (logLevel == LogLevel.HEADERS || logLevel == LogLevel.BODY_AND_HEADERS) {
        for (String header : request.headers().names()) {
            if (!LOGGING_HEADER.equals(header)) {
                log(logger, String.format("%s: %s", header, Joiner.on(", ").join(request.headers(header))));
            }
        }
    }
    // log body
    if (bodyLogging && (logLevel == LogLevel.BODY || logLevel == LogLevel.BODY_AND_HEADERS)) {
        if (request.body() != null) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            Charset charset = Charset.forName("UTF8");
            MediaType contentType = request.body().contentType();
            if (contentType != null) {
                charset = contentType.charset(charset);
            }
            if (isPlaintext(buffer)) {
                String content = buffer.clone().readString(charset);
                if (logLevel.isPrettyJson()) {
                    try {
                        content = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(MAPPER.readValue(content, JsonNode.class));
                    } catch (Exception e) {
                    // swallow, keep original content
                    }
                }
                log(logger, String.format("%s-byte body:\n%s", request.body().contentLength(), content));
                log(logger, "--> END " + request.method());
            } else {
                log(logger, "--> END " + request.method() + " (binary " + request.body().contentLength() + "-byte body omitted)");
            }
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        if (logLevel != LogLevel.NONE) {
            log(logger, "<-- 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 URL
    if (logLevel != LogLevel.NONE) {
        log(logger, String.format("<-- %s %s %s (%s ms, %s body)", response.code(), response.message(), response.request().url(), tookMs, bodySize));
    }
    // log headers
    if (logLevel == LogLevel.HEADERS || logLevel == LogLevel.BODY_AND_HEADERS) {
        for (String header : response.headers().names()) {
            log(logger, String.format("%s: %s", header, Joiner.on(", ").join(response.headers(header))));
        }
    }
    // log body
    if (bodyLogging && (logLevel == LogLevel.BODY || logLevel == LogLevel.BODY_AND_HEADERS)) {
        if (response.body() != null) {
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            Charset charset = Charset.forName("UTF8");
            MediaType contentType = responseBody.contentType();
            if (contentType != null) {
                try {
                    charset = contentType.charset(charset);
                } catch (UnsupportedCharsetException e) {
                    log(logger, "Couldn't decode the response body; charset is likely malformed.");
                    log(logger, "<-- END HTTP");
                    return response;
                }
            }
            boolean gzipped = response.header("content-encoding") != null && StringUtils.containsIgnoreCase(response.header("content-encoding"), "gzip");
            if (!isPlaintext(buffer) && !gzipped) {
                log(logger, "<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }
            String content;
            if (gzipped) {
                content = CharStreams.toString(new InputStreamReader(new GZIPInputStream(buffer.clone().inputStream())));
            } else {
                content = buffer.clone().readString(charset);
            }
            if (logLevel.isPrettyJson()) {
                try {
                    content = MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(MAPPER.readValue(content, JsonNode.class));
                } catch (Exception e) {
                // swallow, keep original content
                }
            }
            log(logger, String.format("%s-byte body:\n%s", buffer.size(), content));
            log(logger, "<-- END HTTP");
        }
    }
    return response;
}
Also used : Buffer(okio.Buffer) InputStreamReader(java.io.InputStreamReader) Request(okhttp3.Request) Charset(java.nio.charset.Charset) Logger(org.slf4j.Logger) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) GZIPInputStream(java.util.zip.GZIPInputStream) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) MediaType(okhttp3.MediaType) BufferedSource(okio.BufferedSource)

Aggregations

MediaType (okhttp3.MediaType)103 RequestBody (okhttp3.RequestBody)95 Request (okhttp3.Request)86 Response (okhttp3.Response)78 IOException (java.io.IOException)73 ResponseBody (okhttp3.ResponseBody)36 BufferedSink (okio.BufferedSink)34 Buffer (okio.Buffer)30 Charset (java.nio.charset.Charset)26 Headers (okhttp3.Headers)19 BufferedSource (okio.BufferedSource)19 Map (java.util.Map)17 OkHttpClient (okhttp3.OkHttpClient)17 InputStream (java.io.InputStream)12 HashMap (java.util.HashMap)12 MultipartBody (okhttp3.MultipartBody)12 MockResponse (okhttp3.mockwebserver.MockResponse)11 EOFException (java.io.EOFException)10 GzipSink (okio.GzipSink)10 JSONObject (org.json.JSONObject)10