Search in sources :

Example 71 with MediaType

use of okhttp3.MediaType in project Signal-Android by WhisperSystems.

the class OkHttpUtil method readAsString.

public static String readAsString(@NonNull ResponseBody body, long sizeLimit) throws IOException {
    if (body.contentLength() > sizeLimit) {
        throw new IOException("Content-Length exceeded maximum size!");
    }
    byte[] data = readAsBytes(body.byteStream(), sizeLimit);
    MediaType contentType = body.contentType();
    Charset charset = contentType != null ? contentType.charset(UTF_8) : UTF_8;
    return new String(data, Objects.requireNonNull(charset));
}
Also used : MediaType(okhttp3.MediaType) Charset(java.nio.charset.Charset) IOException(java.io.IOException)

Example 72 with MediaType

use of okhttp3.MediaType in project okhttp-OkGo by jeasonlzy.

the class HttpLoggingInterceptor method logForResponse.

private Response logForResponse(Response response, long tookMs) {
    Response.Builder builder = response.newBuilder();
    Response clone = builder.build();
    ResponseBody responseBody = clone.body();
    boolean logBody = (printLevel == Level.BODY);
    boolean logHeaders = (printLevel == Level.BODY || printLevel == Level.HEADERS);
    try {
        log("<-- " + clone.code() + ' ' + clone.message() + ' ' + clone.request().url() + " (" + tookMs + "ms)");
        if (logHeaders) {
            Headers headers = clone.headers();
            for (int i = 0, count = headers.size(); i < count; i++) {
                log("\t" + headers.name(i) + ": " + headers.value(i));
            }
            log(" ");
            if (logBody && HttpHeaders.hasBody(clone)) {
                if (responseBody == null)
                    return response;
                if (isPlaintext(responseBody.contentType())) {
                    byte[] bytes = IOUtils.toByteArray(responseBody.byteStream());
                    MediaType contentType = responseBody.contentType();
                    String body = new String(bytes, getCharset(contentType));
                    log("\tbody:" + body);
                    responseBody = ResponseBody.create(responseBody.contentType(), bytes);
                    return response.newBuilder().body(responseBody).build();
                } else {
                    log("\tbody: maybe [binary body], omitted!");
                }
            }
        }
    } catch (Exception e) {
        OkLogger.printStackTrace(e);
    } finally {
        log("<-- END HTTP");
    }
    return response;
}
Also used : Response(okhttp3.Response) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) MediaType(okhttp3.MediaType) IOException(java.io.IOException) ResponseBody(okhttp3.ResponseBody)

Example 73 with MediaType

use of okhttp3.MediaType in project zipkin by openzipkin.

the class ZipkinRuleTest method getTraces_storedViaPostVersion2.

void getTraces_storedViaPostVersion2(String mediaType, SpanBytesEncoder encoder) throws IOException {
    byte[] message = encoder.encodeList(spans);
    // write the span to the zipkin using http api v2
    Response response = client.newCall(new Request.Builder().url(zipkin.httpUrl() + "/api/v2/spans").post(RequestBody.create(MediaType.parse(mediaType), message)).build()).execute();
    assertThat(response.code()).isEqualTo(202);
    // read the traces directly
    assertThat(zipkin.getTraces()).containsOnly(asList(spans.get(0)), asList(spans.get(1)));
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request)

Example 74 with MediaType

use of okhttp3.MediaType in project OkHttp3 by MrZhousf.

the class BaseHelper method matchContentType.

protected RequestBody matchContentType(HttpInfo info, UploadFileInfo fileInfo) {
    RequestBody requestBody;
    MediaType mediaType;
    // 设置请求参数编码格式
    String requestEncoding = info.getRequestEncoding();
    if (TextUtils.isEmpty(requestEncoding)) {
        requestEncoding = ";charset=" + helperInfo.getRequestEncoding().toLowerCase();
    } else {
        requestEncoding = ";charset=" + requestEncoding.toLowerCase();
    }
    // 上传文件
    if (fileInfo != null) {
        String contentType = fileInfo.getContentType();
        contentType = TextUtils.isEmpty(contentType) ? info.getContentType() : contentType;
        mediaType = MediaType.parse(contentType + requestEncoding);
        String filePath = fileInfo.getFilePathWithName();
        if (fileInfo.getFile() != null) {
            if (TextUtils.isEmpty(filePath)) {
                requestBody = RequestBody.create(mediaType, fileInfo.getFile());
            } else {
                requestBody = RequestBody.create(MediaTypeUtil.fetchFileMediaType(filePath, requestEncoding), fileInfo.getFile());
            }
        } else if (fileInfo.getFileByte() != null) {
            requestBody = RequestBody.create(mediaType, fileInfo.getFileByte());
        } else {
            requestBody = RequestBody.create(mediaType, fileInfo.getFile());
        }
        return requestBody;
    }
    // 兼容以前版本(新版本扩展了ContentType)
    if (!TextUtils.isEmpty(info.getContentType())) {
        mediaType = MediaType.parse(info.getContentType() + requestEncoding);
        if (info.getParamBytes() != null) {
            requestBody = RequestBody.create(mediaType, info.getParamBytes());
        } else if (info.getParamFile() != null) {
            requestBody = RequestBody.create(mediaType, info.getParamFile());
        } else if (info.getParamJson() != null) {
            showLog("Params: " + info.getParamJson());
            requestBody = RequestBody.create(mediaType, info.getParamJson());
        } else if (info.getParamForm() != null) {
            showLog("Params: " + info.getParamForm());
            requestBody = RequestBody.create(mediaType, info.getParamForm());
        } else {
            requestBody = packageRequestBody(info, mediaType);
        }
    } else {
        if (info.getParamBytes() != null) {
            requestBody = RequestBody.create(MediaType.parse(ContentType.STREAM + requestEncoding), info.getParamBytes());
        } else if (info.getParamFile() != null) {
            requestBody = RequestBody.create(MediaType.parse(ContentType.MARKDOWN + requestEncoding), info.getParamFile());
        } else if (info.getParamJson() != null) {
            showLog("Params: " + info.getParamJson());
            requestBody = RequestBody.create(MediaType.parse(ContentType.JSON + requestEncoding), info.getParamJson());
        } else if (info.getParamForm() != null) {
            showLog("Params: " + info.getParamForm());
            requestBody = RequestBody.create(MediaType.parse(ContentType.FORM + requestEncoding), info.getParamForm());
        } else {
            requestBody = packageRequestBody(info, MediaType.parse(ContentType.FORM + requestEncoding));
        }
    }
    return requestBody;
}
Also used : MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Example 75 with MediaType

use of okhttp3.MediaType in project chuck by jgilfelt.

the class ChuckInterceptor method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    HttpTransaction transaction = new HttpTransaction();
    transaction.setRequestDate(new Date());
    transaction.setMethod(request.method());
    transaction.setUrl(request.url().toString());
    transaction.setRequestHeaders(request.headers());
    if (hasRequestBody) {
        if (requestBody.contentType() != null) {
            transaction.setRequestContentType(requestBody.contentType().toString());
        }
        if (requestBody.contentLength() != -1) {
            transaction.setRequestContentLength(requestBody.contentLength());
        }
    }
    transaction.setRequestBodyIsPlainText(!bodyHasUnsupportedEncoding(request.headers()));
    if (hasRequestBody && transaction.requestBodyIsPlainText()) {
        BufferedSource source = getNativeSource(new Buffer(), bodyGzipped(request.headers()));
        Buffer buffer = source.buffer();
        requestBody.writeTo(buffer);
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        if (isPlaintext(buffer)) {
            transaction.setRequestBody(readFromBuffer(buffer, charset));
        } else {
            transaction.setResponseBodyIsPlainText(false);
        }
    }
    Uri transactionUri = create(transaction);
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        transaction.setError(e.toString());
        update(transaction, transactionUri);
        throw e;
    }
    long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
    ResponseBody responseBody = response.body();
    // includes headers added later in the chain
    transaction.setRequestHeaders(response.request().headers());
    transaction.setResponseDate(new Date());
    transaction.setTookMs(tookMs);
    transaction.setProtocol(response.protocol().toString());
    transaction.setResponseCode(response.code());
    transaction.setResponseMessage(response.message());
    transaction.setResponseContentLength(responseBody.contentLength());
    if (responseBody.contentType() != null) {
        transaction.setResponseContentType(responseBody.contentType().toString());
    }
    transaction.setResponseHeaders(response.headers());
    transaction.setResponseBodyIsPlainText(!bodyHasUnsupportedEncoding(response.headers()));
    if (HttpHeaders.hasBody(response) && transaction.responseBodyIsPlainText()) {
        BufferedSource source = getNativeSource(response);
        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) {
                update(transaction, transactionUri);
                return response;
            }
        }
        if (isPlaintext(buffer)) {
            transaction.setResponseBody(readFromBuffer(buffer.clone(), charset));
        } else {
            transaction.setResponseBodyIsPlainText(false);
        }
        transaction.setResponseContentLength(buffer.size());
    }
    update(transaction, transactionUri);
    return response;
}
Also used : Buffer(okio.Buffer) HttpTransaction(com.readystatesoftware.chuck.internal.data.HttpTransaction) Request(okhttp3.Request) Charset(java.nio.charset.Charset) Uri(android.net.Uri) Date(java.util.Date) 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) RequestBody(okhttp3.RequestBody) 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