Search in sources :

Example 36 with MediaType

use of okhttp3.MediaType in project AndoridLib by twp520.

the class HttpLogInterceptor method logForResponse.

private Response logForResponse(Response response) {
    try {
        // ===>response log
        if (showLog) {
            Log.e(tag, "********响应日志开始********");
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            Log.e(tag, "url : " + clone.request().url());
            Log.e(tag, "code : " + clone.code());
            if (!TextUtils.isEmpty(clone.message()))
                Log.e(tag, "message : " + clone.message());
            ResponseBody body = clone.body();
            if (body != null) {
                MediaType mediaType = body.contentType();
                if (mediaType != null) {
                    if (isText(mediaType)) {
                        String resp = body.string();
                        // String res = Des3.decode(resp);
                        Log.e(tag, "响应内容: " + resp);
                        Log.e(tag, "********响应日志结束********");
                        body = ResponseBody.create(mediaType, resp);
                        return response.newBuilder().body(body).build();
                    } else {
                        Log.e(tag, "响应内容 : " + " 发生错误");
                    }
                }
            }
            Log.e(tag, "********响应日志结束********");
        }
    } catch (Exception e) {
    // e.printStackTrace();
    }
    return response;
}
Also used : Response(okhttp3.Response) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 37 with MediaType

use of okhttp3.MediaType in project gh4a by slapperwan.

the class HttpImageGetter method loadImageForUrl.

private Drawable loadImageForUrl(String source) {
    HttpUrl url = source != null ? HttpUrl.parse(source) : null;
    Bitmap bitmap = null;
    if (!mDestroyed && url != null) {
        File output = null;
        InputStream is = null;
        Request request = new Request.Builder().url(url).build();
        try (Response response = mClient.newCall(request).execute()) {
            is = response.body().byteStream();
            if (is != null) {
                MediaType mediaType = response.body().contentType();
                String mime = mediaType != null ? mediaType.toString() : null;
                if (mime == null) {
                    mime = URLConnection.guessContentTypeFromName(source);
                }
                if (mime == null) {
                    mime = URLConnection.guessContentTypeFromStream(is);
                }
                if (mime != null && mime.startsWith("image/svg")) {
                    bitmap = renderSvgToBitmap(mContext.getResources(), is, mWidth, mHeight);
                } else {
                    boolean isGif = mime != null && mime.startsWith("image/gif");
                    if (!isGif || canLoadGif()) {
                        output = File.createTempFile("image", ".tmp", mCacheDir);
                        if (FileUtils.save(output, is)) {
                            if (isGif) {
                                GifDrawable d = new GifDrawable(output);
                                d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
                                return d;
                            } else {
                                bitmap = getBitmap(output, mWidth, mHeight);
                            }
                        }
                    }
                }
            }
        } catch (IOException e) {
        // fall through to showing the error bitmap
        } finally {
            if (output != null) {
                output.delete();
            }
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                // ignored
                }
            }
        }
    }
    synchronized (this) {
        if (mDestroyed && bitmap != null) {
            bitmap.recycle();
            bitmap = null;
        }
    }
    if (bitmap == null) {
        return mErrorDrawable;
    }
    BitmapDrawable drawable = new LoadedBitmapDrawable(mContext.getResources(), bitmap);
    drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
    return drawable;
}
Also used : InputStream(java.io.InputStream) Request(okhttp3.Request) GifDrawable(pl.droidsonroids.gif.GifDrawable) IOException(java.io.IOException) BitmapDrawable(android.graphics.drawable.BitmapDrawable) HttpUrl(okhttp3.HttpUrl) Response(okhttp3.Response) Bitmap(android.graphics.Bitmap) MediaType(okhttp3.MediaType) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File)

Example 38 with MediaType

use of okhttp3.MediaType in project BaseProject by wareine.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    // 请求服务器的url
    String url = request.url().toString();
    // 请求方法
    String method = request.method();
    long t1 = System.nanoTime();
    LogUtils.d(TAG, String.format(Locale.getDefault(), "Send Method : %s, Request Url : %s", method, url));
    // request body(请求体)
    RequestBody requestBody = request.body();
    if (null != requestBody) {
        StringBuilder sb = new StringBuilder("Request Body [");
        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = requestBody.contentType();
        if (null != contentType) {
            charset = contentType.charset();
            if (null == charset) {
                charset = Charset.forName("UTF-8");
            }
        }
        if (isPlaintext(buffer)) {
            sb.append(buffer.readString(charset));
            if (null != contentType) {
                sb.append("(Content-Type = ").append(contentType.toString()).append(", ").append(requestBody.contentLength()).append("-byte body");
            }
        } else {
            if (null != contentType) {
                sb.append("(Content-Type = ").append(contentType.toString()).append(", binary").append(requestBody.contentLength()).append("-byte body omitted");
            }
        }
        sb.append("]");
        LogUtils.d(TAG, String.format(Locale.getDefault(), "%s %s", method, sb.toString()));
    }
    Response response = chain.proceed(request);
    long t2 = System.nanoTime();
    // 打印响应时间
    LogUtils.d(TAG, String.format(Locale.getDefault(), "Received response for [url = %s] in %.1fms", url, (t2 - t1) / 1e6d));
    // 响应状态,是否成功
    LogUtils.d(TAG, String.format(Locale.CHINA, "Received response is %s, message [%s], code[%d]", response.isSuccessful() ? "success" : "fail", response.message(), response.code()));
    // 响应头
    LogUtils.d(TAG, String.format(Locale.getDefault(), "Received response header is %s", response.headers().toString()));
    // 从网络上获取数据时打印相关信息
    LogUtils.d(TAG, "Received network response message is : " + response.networkResponse());
    // 从缓存上获取数据时打印相关信息
    LogUtils.d(TAG, "Received cache response message is : " + response.cacheResponse());
    // 响应数据
    ResponseBody body = response.body();
    BufferedSource source = body.source();
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    Charset charset = Charset.defaultCharset();
    MediaType contentType = body.contentType();
    if (null != contentType) {
        charset = contentType.charset(charset);
    }
    String bodyString = buffer.clone().readString(charset);
    LogUtils.d(TAG, String.format(Locale.getDefault(), "Received response json string [%s]", bodyString));
    return response;
}
Also used : Buffer(okio.Buffer) Response(okhttp3.Response) Request(okhttp3.Request) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

Example 39 with MediaType

use of okhttp3.MediaType in project BaseProject by wareine.

the class UploadFileManager method createProgressRequestBody.

/**
 * 创建带进度的RequestBody
 * @param contentType MediaType
 * @param file  准备上传的文件
 * @param callBack 回调
 * @param <T>
 * @return
 */
public <T> RequestBody createProgressRequestBody(final MediaType contentType, final File file, final ReqProgressCallBack<T> callBack) {
    return new RequestBody() {

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

        @Override
        public long contentLength() {
            return file.length();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            Source source;
            try {
                source = Okio.source(file);
                Buffer buf = new Buffer();
                long remaining = contentLength();
                long current = 0;
                for (long readCount; (readCount = source.read(buf, 2048)) != -1; ) {
                    sink.write(buf, readCount);
                    current += readCount;
                    Log.e(TAG, "current------>" + current);
                    progressCallBack(remaining, current, callBack);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
}
Also used : Buffer(okio.Buffer) BufferedSink(okio.BufferedSink) Source(okio.Source) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Example 40 with MediaType

use of okhttp3.MediaType in project BaseProject by wareine.

the class LoggingInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    // 请求服务器的url
    String url = request.url().toString();
    // 请求方法
    String method = request.method();
    long t1 = System.nanoTime();
    LogUtils.d(TAG, String.format(Locale.getDefault(), "Send Method : %s, Request Url : %s", method, url));
    // request body(请求体)
    RequestBody requestBody = request.body();
    if (null != requestBody) {
        StringBuilder sb = new StringBuilder("Request Body [");
        Buffer buffer = new Buffer();
        requestBody.writeTo(buffer);
        Charset charset = Charset.forName("UTF-8");
        MediaType contentType = requestBody.contentType();
        if (null != contentType) {
            charset = contentType.charset();
            if (null == charset) {
                charset = Charset.forName("UTF-8");
            }
        }
        if (isPlaintext(buffer)) {
            sb.append(buffer.readString(charset));
            if (null != contentType) {
                sb.append("(Content-Type = ").append(contentType.toString()).append(", ").append(requestBody.contentLength()).append("-byte body");
            }
        } else {
            if (null != contentType) {
                sb.append("(Content-Type = ").append(contentType.toString()).append(", binary").append(requestBody.contentLength()).append("-byte body omitted");
            }
        }
        sb.append("]");
        LogUtils.d(TAG, String.format(Locale.getDefault(), "%s %s", method, sb.toString()));
    }
    Response response = chain.proceed(request);
    long t2 = System.nanoTime();
    // 打印响应时间
    LogUtils.d(TAG, String.format(Locale.getDefault(), "Received response for [url = %s] in %.1fms", url, (t2 - t1) / 1e6d));
    // 响应状态,是否成功
    LogUtils.d(TAG, String.format(Locale.CHINA, "Received response is %s, message [%s], code[%d]", response.isSuccessful() ? "success" : "fail", response.message(), response.code()));
    // 响应头
    LogUtils.d(TAG, String.format(Locale.getDefault(), "Received response header is %s", response.headers().toString()));
    // 从网络上获取数据时打印相关信息
    LogUtils.d(TAG, "Received network response message is : " + response.networkResponse());
    // 从缓存上获取数据时打印相关信息
    LogUtils.d(TAG, "Received cache response message is : " + response.cacheResponse());
    // 响应数据
    ResponseBody body = response.body();
    BufferedSource source = body.source();
    source.request(Long.MAX_VALUE);
    Buffer buffer = source.buffer();
    Charset charset = Charset.defaultCharset();
    MediaType contentType = body.contentType();
    if (null != contentType) {
        charset = contentType.charset(charset);
    }
    String bodyString = buffer.clone().readString(charset);
    LogUtils.d(TAG, String.format(Locale.getDefault(), "Received response json string [%s]", bodyString));
    return response;
}
Also used : Buffer(okio.Buffer) Response(okhttp3.Response) Request(okhttp3.Request) Charset(java.nio.charset.Charset) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody) ResponseBody(okhttp3.ResponseBody) BufferedSource(okio.BufferedSource)

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