Search in sources :

Example 76 with MediaType

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

the class ANRequest method getMultiPartRequestBody.

public RequestBody getMultiPartRequestBody() {
    MultipartBody.Builder builder = new MultipartBody.Builder().setType((customMediaType == null) ? MultipartBody.FORM : customMediaType);
    try {
        for (HashMap.Entry<String, MultipartStringBody> entry : mMultiPartParameterMap.entrySet()) {
            MultipartStringBody stringBody = entry.getValue();
            MediaType mediaType = null;
            if (stringBody.contentType != null) {
                mediaType = MediaType.parse(stringBody.contentType);
            }
            builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\""), RequestBody.create(mediaType, stringBody.value));
        }
        for (HashMap.Entry<String, List<MultipartFileBody>> entry : mMultiPartFileMap.entrySet()) {
            List<MultipartFileBody> fileBodies = entry.getValue();
            for (MultipartFileBody fileBody : fileBodies) {
                String fileName = fileBody.file.getName();
                MediaType mediaType;
                if (fileBody.contentType != null) {
                    mediaType = MediaType.parse(fileBody.contentType);
                } else {
                    mediaType = MediaType.parse(Utils.getMimeType(fileName));
                }
                RequestBody requestBody = RequestBody.create(mediaType, fileBody.file);
                builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + entry.getKey() + "\"; filename=\"" + fileName + "\""), requestBody);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return builder.build();
}
Also used : MultipartStringBody(com.androidnetworking.model.MultipartStringBody) HashMap(java.util.HashMap) MultipartFileBody(com.androidnetworking.model.MultipartFileBody) MultipartBody(okhttp3.MultipartBody) MediaType(okhttp3.MediaType) List(java.util.List) ArrayList(java.util.ArrayList) RequestBody(okhttp3.RequestBody)

Example 77 with MediaType

use of okhttp3.MediaType in project FlareBot by FlareBot.

the class WebUtils method post.

public static Response post(String url, MediaType type, String body, boolean sendAPIAuth, boolean compress) throws IOException {
    Request.Builder request = new Request.Builder().url(url);
    if (sendAPIAuth)
        request.addHeader("Authorization", FlareBot.instance().getApiKey());
    if (compress)
        request.addHeader("Content-Encoding", "gzip");
    RequestBody requestBody = RequestBody.create(type, body);
    request = request.post(requestBody);
    return request(request);
}
Also used : Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Example 78 with MediaType

use of okhttp3.MediaType in project FlareBot by FlareBot.

the class ApiRequester method getRequest.

private static Request getRequest(ApiRoute route, String bodyContent, MediaType type, boolean compressed) {
    Request.Builder request = new Request.Builder().url(route.getFullUrl());
    request.addHeader("Authorization", FlareBot.instance().getApiKey());
    request.addHeader("User-Agent", "Mozilla/5.0 FlareBot");
    RequestBody body = RequestBody.create(JSON, bodyContent);
    if (compressed && !bodyContent.isEmpty()) {
        request.addHeader("Content-Encoding", "gzip");
        logger.debug("Starting compression: " + System.currentTimeMillis());
        byte[] output = new byte[100];
        Deflater deflater = new Deflater();
        deflater.setInput(bodyContent.getBytes());
        deflater.finish();
        deflater.deflate(output);
        deflater.end();
        logger.debug("Finished compression: " + System.currentTimeMillis());
        body = RequestBody.create(type, output);
    }
    logger.debug("Sending " + route.getRoute() + ", Type: " + type.toString() + ", Compressed: " + compressed);
    switch(route.getMethod()) {
        case GET:
            request = request.get();
            break;
        case PATCH:
            request = request.patch(body);
            break;
        case POST:
            request = request.post(body);
            break;
        case PUT:
            request = request.put(body);
            break;
        case DELETE:
            request = request.delete(body);
            break;
        default:
            throw new IllegalArgumentException("The route " + route.name() + " is using an unsupported method! Method: " + route.getMethod().name());
    }
    return request.build();
}
Also used : Deflater(java.util.zip.Deflater) Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Example 79 with MediaType

use of okhttp3.MediaType in project FlareBot by FlareBot.

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
        @ParametersAreNonnullByDefault
        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 80 with MediaType

use of okhttp3.MediaType in project mobile-sdk-android by meniga.

the class MenigaHttpLogger method intercept.

@Override
public Response intercept(Chain chain) throws IOException {
    Request request = chain.request();
    if (logLevel == LogLevel.NONE) {
        return chain.proceed(request);
    }
    boolean logBody = logType == LogType.BODY_ONLY || logType == LogType.BODY_AND_HEADERS;
    boolean logHeaders = logType == LogType.HEADERS_ONLY || logType == LogType.BODY_AND_HEADERS;
    RequestBody requestBody = request.body();
    boolean hasRequestBody = requestBody != null;
    String reqUrl = request.url().toString();
    String requestStartMessage = request.method() + REQUEST_START + reqUrl;
    if (!logHeaders && hasRequestBody) {
        requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
    }
    log(requestStartMessage);
    if (logHeaders) {
        if (hasRequestBody) {
            // them to be included (when available) so their values are known.
            if (requestBody.contentType() != null) {
                log(getHeaderString("Content-Type", requestBody.contentType().toString()));
            }
            if (requestBody.contentLength() != -1) {
                log(getHeaderString("Content-Length", Long.toString(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)) {
                log(getHeaderString(name, headers.value(i)));
            }
        }
    }
    if (!logBody) {
        log(REQUEST_END + request.method());
    } else if (!hasRequestBody) {
        log(BODY);
        log(NO_BODY);
    } else if (bodyEncoded(request.headers())) {
        log(REQUEST_END + request.method() + " (encoded body omitted)");
    } else {
        Buffer buffer = new Buffer();
        try {
            requestBody.writeTo(buffer);
        } catch (ConcurrentModificationException ex) {
            log("Error logging body - got ConcurrentModificationException");
        }
        Charset charset = UTF8;
        MediaType contentType = requestBody.contentType();
        if (contentType != null) {
            charset = contentType.charset(UTF8);
        }
        log(BODY);
        if (isPlaintext(buffer)) {
            log(buffer.readString(charset));
            log(REQUEST_END + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        } else {
            log("<" + requestBody.contentLength() + "-BYTE BINARY BODY OMITTED");
            log(REQUEST_END + request.method());
        }
    }
    long startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);
    } catch (Exception e) {
        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";
    log(RESPONSE_START + reqUrl);
    log("(" + tookMs + "ms" + (!logHeaders ? ", " + bodySize + " body" : "") + ")");
    if (logHeaders) {
        Headers headers = response.headers();
        for (int i = 0, count = headers.size(); i < count; i++) {
            log(getHeaderString(headers.name(i), headers.value(i)));
        }
    }
    if (!logBody) {
        log(RESPONSE_END);
    } else if (!HttpHeaders.hasBody(response)) {
        log(BODY);
        log(NO_BODY);
        log(RESPONSE_END);
    } else if (bodyEncoded(response.headers())) {
        log(BODY);
        log("<ENCODED BODY OMITTED>");
        log(RESPONSE_END);
    } 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) {
            try {
                charset = contentType.charset(UTF8);
            } catch (UnsupportedCharsetException e) {
                log(BODY);
                log("<ERROR DECODING BODY; CHARSET IS LIKELY MALFORMED.>");
                log(RESPONSE_END);
                return response;
            }
        }
        if (!isPlaintext(buffer)) {
            log(BODY);
            log("<BINARY " + buffer.size() + "-BYTE BODY OMITTED>");
            log(RESPONSE_END);
            return response;
        }
        if (contentLength != 0) {
            log(BODY + " (" + buffer.size() + "-byte body)");
            log(buffer.clone().readString(charset));
        }
        log(RESPONSE_END);
    }
    return response;
}
Also used : Buffer(okio.Buffer) ConcurrentModificationException(java.util.ConcurrentModificationException) HttpHeaders(okhttp3.internal.http.HttpHeaders) Headers(okhttp3.Headers) Request(okhttp3.Request) Charset(java.nio.charset.Charset) IOException(java.io.IOException) EOFException(java.io.EOFException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) ConcurrentModificationException(java.util.ConcurrentModificationException) 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