Search in sources :

Example 36 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project WorkHelperApp by hubme.

the class HttpLoggingInterceptor 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);
    }
    boolean logBody = level == Level.BODY;
    boolean logHeaders = logBody || level == Level.HEADERS;
    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 (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    logger.log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so there values are known.
            if (requestBody.contentType() != null) {
                logger.log("Content-Type: " + requestBody.contentType());
            }
            if (requestBody.contentLength() != -1) {
                logger.log("Content-Length: " + requestBody.contentLength());
            }
        }
        Headers headers = request.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            String name = headers.name(i);
            // Skip headers from the request body as they are explicitly logged above.
            if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
                logger.log(name + ": " + headers.value(i));
            }
        }
        if (!logBody || !hasRequestBody) {
            logger.log("--> END " + request.method());
        } else if (bodyEncoded(request.headers())) {
            logger.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);
            }
            logger.log("");
            if (isPlaintext(buffer)) {
                logger.log(buffer.readString(charset));
                logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
            } else {
                logger.log("--> END " + request.method() + " (binary " + requestBody.contentLength() + "-byte body omitted)");
            }
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        logger.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";
    logger.log("<-- " + response.code() + ' ' + response.message() + ' ' + response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ')');
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            logger.log(headers.name(i) + ": " + headers.value(i));
        }
        if (!logBody || !HttpHeaders.hasBody(response)) {
            logger.log("<-- END HTTP");
        } else if (bodyEncoded(response.headers())) {
            logger.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) {
                charset = contentType.charset(UTF8);
            }
            if (!isPlaintext(buffer)) {
                logger.log("");
                logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
                return response;
            }
            if (contentLength != 0) {
                logger.log("");
                logger.log(buffer.clone().readString(charset));
            }
            logger.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) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 37 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project WorkHelperApp by hubme.

the class LogInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    String bodyString;
    long t1 = System.nanoTime();
    Response response = chain.proceed(request);
    if (SPUtil.getBoolean(GlobalConstant.SP_PARAMS_KEY.INTERCEPTOR_LOG_DISABLE)) {
        return response;
    }
    String time = String.format(Locale.getDefault(), "%.1fms", (System.nanoTime() - t1) / 1e6d);
    try {
        MediaType mediaType = null;
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            mediaType = responseBody.contentType();
        }
        if (isPlaintext(mediaType)) {
            // responseBody只能被消费一次。否则执行回调时会出错:IllegalStateException: closed.
            BufferedSource source = responseBody.source();
            // Buffer the entire body.
            source.request(Long.MAX_VALUE);
            Buffer buffer = source.buffer();
            bodyString = buffer.clone().readString(Charset.defaultCharset());
            printLog(request, response, time, mediaType, bodyString);
        } else {
            String mime = (mediaType == null ? "null" : mediaType.toString());
            Logger.log(Logger.INFO, AppConfig.LOG_TAG, "url: " + request.url().toString() + "  MIME类型是:" + mime + ",不打印log.");
        }
    } catch (SocketTimeoutException e) {
        printLog(request, null, "超时", null, null);
        return chain.proceed(chain.request());
    } catch (Exception e) {
        printLog(request, null, "失败.可能断网、接口挂了", null, null);
        return chain.proceed(chain.request());
    }
    return response;
}
Also used : Response(okhttp3.Response) Buffer(okio.Buffer) SocketTimeoutException(java.net.SocketTimeoutException) Request(okhttp3.Request) MediaType(okhttp3.MediaType) IOException(java.io.IOException) SocketTimeoutException(java.net.SocketTimeoutException) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 38 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project WorkHelperApp by hubme.

the class OkHttpFragment method onUploadFileClick.

@OnClick(R.id.tv_upload_file)
public void onUploadFileClick() {
    MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
    File file = new File("");
    Request request = new Request.Builder().url("").post(RequestBody.create(MEDIA_TYPE_MARKDOWN, file)).build();
    mOkHttpClient.newCall(request).enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {
        }
    });
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) Callback(okhttp3.Callback) Request(okhttp3.Request) MediaType(okhttp3.MediaType) IOException(java.io.IOException) File(java.io.File) OnClick(butterknife.OnClick)

Example 39 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project vcita-client-java-sdk by SimonIT.

the class OAuthOkHttpClient method execute.

@Override
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(request.getBody(), mediaType) : 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(), 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 40 with MediaType

use of com.reprezen.kaizen.oasparser.model3.MediaType in project RxEasyHttp by zhou-you.

the class BaseExpiredInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    Response response = chain.proceed(request);
    ResponseBody responseBody = response.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);
    HttpLog.i("网络拦截器:" + bodyString + " host:" + request.url().toString());
    boolean isText = isText(contentType);
    if (!isText) {
        return response;
    }
    // 判断响应是否过期(无效)
    if (isResponseExpired(response, bodyString)) {
        return responseExpired(chain, bodyString);
    }
    return response;
}
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)

Aggregations

MediaType (okhttp3.MediaType)297 RequestBody (okhttp3.RequestBody)186 Request (okhttp3.Request)179 Response (okhttp3.Response)158 IOException (java.io.IOException)137 ResponseBody (okhttp3.ResponseBody)71 OkHttpClient (okhttp3.OkHttpClient)68 Charset (java.nio.charset.Charset)50 Buffer (okio.Buffer)50 Headers (okhttp3.Headers)48 JSONObject (org.json.JSONObject)38 BufferedSource (okio.BufferedSource)36 MultipartBody (okhttp3.MultipartBody)34 HttpUrl (okhttp3.HttpUrl)30 Map (java.util.Map)24 BufferedSink (okio.BufferedSink)23 File (java.io.File)22 InputStream (java.io.InputStream)21 ArrayList (java.util.ArrayList)21 Test (org.junit.Test)21