Search in sources :

Example 26 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) {
        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)

Example 27 with MediaType

use of okhttp3.MediaType in project openhab-android by openhab.

the class MySyncHttpClient method method.

protected Response method(String url, String method, Map<String, String> addHeaders, String requestBody, String mediaType, final ResponseHandler responseHandler) {
    Request.Builder requestBuilder = new Request.Builder();
    requestBuilder.url(getBaseUrl().newBuilder(url).build());
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        requestBuilder.addHeader(entry.getKey(), entry.getValue());
    }
    if (addHeaders != null) {
        for (Map.Entry<String, String> entry : addHeaders.entrySet()) {
            requestBuilder.addHeader(entry.getKey(), entry.getValue());
        }
    }
    if (requestBody != null) {
        requestBuilder.method(method, RequestBody.create(MediaType.parse(mediaType), requestBody));
    }
    Request request = requestBuilder.build();
    Call call = client.newCall(request);
    try {
        Response resp = call.execute();
        if (resp.isSuccessful()) {
            responseHandler.onSuccess(call, resp.code(), resp.headers(), resp.body().bytes());
        } else {
            responseHandler.onFailure(call, resp.code(), resp.headers(), resp.body().bytes(), new IOException(resp.code() + ": " + resp.message()));
        }
        return resp;
    } catch (IOException ex) {
        responseHandler.onFailure(call, 0, new Headers.Builder().build(), null, ex);
        return new Response.Builder().code(500).message(ex.getClass().getName() + ": " + ex.getMessage()).request(request).protocol(Protocol.HTTP_1_0).build();
    }
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) Headers(okhttp3.Headers) Request(okhttp3.Request) IOException(java.io.IOException) Map(java.util.Map)

Example 28 with MediaType

use of okhttp3.MediaType in project HttpApiDemo by xiaoyunchengzhu.

the class DataMeature method generateMultipartRequestBody.

/**
 * HttpParam  表单 处理
 * @param httpParam
 * @return
 */
private static RequestBody generateMultipartRequestBody(HttpParam httpParam) {
    if (httpParam.getFiles().isEmpty()) {
        // 表单提交,没有文件
        FormBody.Builder bodyBuilder = new FormBody.Builder();
        for (String key : httpParam.getMap().keySet()) {
            bodyBuilder.add(key, httpParam.getMap().get(key));
        }
        return bodyBuilder.build();
    // RequestUtfBody.Builder bodyBuilder = new RequestUtfBody.Builder();
    // 
    // for (String key : httpParam.getMap().keySet()) {
    // bodyBuilder.add(key, httpParam.getMap().get(key));
    // }
    // return bodyBuilder.build();
    } else {
        // 表单提交,有文件
        MultipartBody.Builder multipartBodybuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        // 拼接键值对
        if (!httpParam.getMap().isEmpty()) {
            for (Map.Entry<String, String> entry : httpParam.getMap().entrySet()) {
                multipartBodybuilder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }
        // 拼接文件
        for (String entry : httpParam.getFiles().keySet()) {
            MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
            RequestBody fileBody = RequestBody.create(mediaType, httpParam.getFiles().get(entry));
            multipartBodybuilder.addFormDataPart(entry, entry, fileBody);
        }
        return multipartBodybuilder.build();
    }
}
Also used : MultipartBody(okhttp3.MultipartBody) FormBody(okhttp3.FormBody) MediaType(okhttp3.MediaType) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 29 with MediaType

use of okhttp3.MediaType in project samourai-wallet-android by Samourai-Wallet.

the class WebUtil method tor_postURL.

public String tor_postURL(String URL, String jsonToString, Map<String, String> headers) throws Exception {
    final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    RequestBody body = RequestBody.create(JSON, jsonToString);
    OkHttpClient.Builder builder = new OkHttpClient.Builder().proxy(TorManager.getInstance(this.context).getProxy());
    if (URL.contains("onion")) {
        getHostNameVerifier(builder);
    }
    if (BuildConfig.DEBUG) {
        builder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    }
    Request.Builder rb = new Request.Builder();
    // set headers
    if (headers == null) {
        headers = new HashMap<>();
    }
    for (Map.Entry<String, String> e : headers.entrySet()) {
        rb = rb.header(e.getKey(), e.getValue());
    }
    Request request = rb.url(URL).post(body).build();
    try (Response response = builder.build().newCall(request).execute()) {
        if (response.body() == null) {
            return "";
        }
        return response.body().string();
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) Response(okhttp3.Response) HttpResponse(ch.boye.httpclientandroidlib.HttpResponse) MediaType(okhttp3.MediaType) HashMap(java.util.HashMap) Map(java.util.Map) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) RequestBody(okhttp3.RequestBody)

Example 30 with MediaType

use of okhttp3.MediaType in project LibTest by liudao01.

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();
    HttpTransaction transactionView = new HttpTransaction();
    // 时间
    transaction.setRequestDate(new Date());
    // 请求方法
    transaction.setMethod(request.method());
    // 请求url
    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.responseBodyIsPlainText()) {
        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)) {
            if (!contentType.toString().contains("multipart/form-data")) {
                String s = readFromBuffer(buffer, charset);
                String requestStr;
                try {
                    requestStr = decode(s);
                } catch (Exception e) {
                    requestStr = s;
                }
                String string = converStr(requestStr);
                try {
                    // requestStrLast = string;
                    requestStrLast = JsonFormatUtil.formatJson(string);
                } catch (Exception e) {
                    requestStrLast = string;
                }
            } else {
                requestStrLast = "";
                return null;
            }
            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());
        try {
            transactionView = transaction;
            transactionView.setRequestBody(requestStrLast);
            TestLibUtil.getInstance().sendmessage(transactionView);
        } catch (Exception e1) {
            e1.printStackTrace();
            TestLibUtil.getInstance().sendmessage(transactionView);
        }
        // TestLibUtil.getInstance().sendmessage(transactionView);
        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);
                try {
                    transactionView = transaction;
                    transactionView.setRequestBody(requestStrLast);
                    TestLibUtil.getInstance().sendmessage(transactionView);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
                return response;
            }
        }
        if (isPlaintext(buffer)) {
            try {
                responseStrLast = JsonFormatUtil.formatJson(readFromBuffer(buffer.clone(), charset));
            } catch (Exception e) {
                responseStrLast = readFromBuffer(buffer.clone(), charset);
            }
            transaction.setResponseBody(readFromBuffer(buffer.clone(), charset));
        } else {
            transaction.setResponseBodyIsPlainText(false);
        }
        transaction.setResponseContentLength(buffer.size());
    }
    try {
        transactionView = transaction;
        transactionView.setRequestBody(requestStrLast);
        transactionView.setResponseBody(responseStrLast);
        TestLibUtil.getInstance().sendmessage(transactionView);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return response;
}
Also used : Buffer(okio.Buffer) HttpTransaction(lib.data.HttpTransaction) Request(okhttp3.Request) Charset(java.nio.charset.Charset) 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)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