Search in sources :

Example 51 with MediaType

use of okhttp3.MediaType in project Fast-Android-Networking by amitshekhariitbhu.

the class GzipRequestInterceptor method forceContentLength.

private RequestBody forceContentLength(final RequestBody requestBody) throws IOException {
    final Buffer buffer = new Buffer();
    requestBody.writeTo(buffer);
    return new RequestBody() {

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

        @Override
        public long contentLength() {
            return buffer.size();
        }

        @Override
        public void writeTo(BufferedSink sink) throws IOException {
            sink.write(buffer.snapshot());
        }
    };
}
Also used : Buffer(okio.Buffer) BufferedSink(okio.BufferedSink) RequestBody(okhttp3.RequestBody)

Example 52 with MediaType

use of okhttp3.MediaType in project Fast-Android-Networking by amitshekhariitbhu.

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 53 with MediaType

use of okhttp3.MediaType in project Fast-Android-Networking by amitshekhariitbhu.

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 54 with MediaType

use of okhttp3.MediaType in project HL4A by HL4A.

the class QCloudUploader method uploadFile.

private void uploadFile() throws 后端错误 {
    try {
        if (AVOSCloud.showInternalDebugLog()) {
            LogUtil.log.d("upload as whole file");
        }
        byte[] bytes = avFile.getData();
        fileSha = AVUtils.SHA1(bytes);
        MultipartBody.Builder builder = new MultipartBody.Builder();
        RequestBody fileBody = RequestBody.create(MediaType.parse(APPLICATION_OCTET_STREAM), bytes, 0, getCurrentSliceLength(0, bytes.length));
        builder.addFormDataPart(FILE_CONTENT, fileKey, fileBody);
        builder.addFormDataPart(PARAM_OP, OP_UPLOAD);
        builder.addFormDataPart(PARAM_SHA, fileSha);
        MediaType type = MediaType.parse(MULTIPART_FORM_DATA);
        if (null != type) {
            builder.setType(type);
        }
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(uploadUrl);
        requestBuilder.header(HEADER_AUTHORIZATION, token);
        requestBuilder.header(HEADER_CONTENT_TYPE, MULTIPART_FORM_DATA);
        for (String key : FileUploader.UPLOAD_HEADERS.keySet()) {
            requestBuilder.header(key, FileUploader.UPLOAD_HEADERS.get(key));
        }
        requestBuilder.post(builder.build());
        Request request = requestBuilder.build();
        Response response = executeWithRetry(request, RETRY_TIMES);
        if (response.code() != 200) {
            throw AVErrorUtils.createException(后端错误.OTHER_CAUSE, AVUtils.stringFromBytes(response.body().bytes()));
        }
    } catch (Exception e) {
        if (AVOSCloud.isDebugLogEnabled()) {
            LogUtil.avlog.e("Exception during file upload", e);
        }
        throw AVErrorUtils.createException(e, "Exception during file upload");
    }
}
Also used : Response(okhttp3.Response) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 55 with MediaType

use of okhttp3.MediaType in project HL4A by HL4A.

the class QCloudUploader method uploadControlSlice.

private JSONObject uploadControlSlice(String token, String url, byte[] wholeFile) throws 后端错误 {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    try {
        String fileSha = AVUtils.SHA1(wholeFile);
        builder.addFormDataPart(PARAM_SHA, fileSha);
        builder.addFormDataPart(PARAM_OP, OP_UPLOAD_SLICE);
        builder.addFormDataPart(PARAM_FILE_SIZE, String.valueOf(wholeFile.length));
        builder.addFormDataPart(PARAM_SLICE_SIZE, String.valueOf(DEFAULT_SLICE_LEN));
        MediaType type = MediaType.parse(MULTIPART_FORM_DATA);
        if (null != type) {
            builder.setType(type);
        }
        Request.Builder requestBuilder = new Request.Builder();
        requestBuilder.url(url);
        requestBuilder.header(HEADER_AUTHORIZATION, token);
        requestBuilder.header(HEADER_CONTENT_TYPE, MULTIPART_FORM_DATA);
        requestBuilder.post(builder.build());
        Request request = requestBuilder.build();
        Response response = executeWithRetry(request, RETRY_TIMES);
        if (response != null) {
            byte[] responseBody = response.body().bytes();
            return parseSliceUploadResponse(AVUtils.stringFromBytes(responseBody));
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new 后端错误(后端错误.OTHER_CAUSE, "Upload file failure");
    }
    return null;
}
Also used : Response(okhttp3.Response) com.avos.avoscloud.后端错误(com.avos.avoscloud.后端错误) MultipartBody(okhttp3.MultipartBody) Request(okhttp3.Request) MediaType(okhttp3.MediaType)

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