Search in sources :

Example 86 with RequestBody

use of okhttp3.RequestBody in project amhttp by Eddieyuan123.

the class RequestManager method upload.

public <T> void upload(Context context, String url, CacheControl cacheControl, HashMap<String, String> headers, File file, String fileName, HashMap<String, String> params, Object tag, final OnUploadListener<T> listener) {
    try {
        IRequestBodyFactory requestBodyFactory = new RequestBodyFactoryImpl();
        RequestBody requestBody = requestBodyFactory.buildRequestBody(file, fileName, params);
        final Request request = new Request.Builder().cacheControl(cacheControl == null ? CacheControl.FORCE_NETWORK : cacheControl).headers(Headers.of(headers)).tag(tag == null ? context.hashCode() : tag).url(url).post(new ProgressRequestBody(requestBody, new ProgressRequestListener() {

            @Override
            public void onRequestProgress(final long bytesWritten, final long contentLength, final boolean done) {
                if (listener != null) {
                    Dispatcher dispatcher = Dispatcher.getDispatcher(Looper.getMainLooper());
                    dispatcher.setRequestListener(listener);
                    Message message = Message.obtain();
                    message.what = MessageConstant.MESSAGE_UPLOAD_PROGRESS;
                    Bundle bundle = new Bundle();
                    bundle.putLong("bytesWritten", bytesWritten);
                    bundle.putLong("contentLength", contentLength);
                    bundle.putBoolean("done", done);
                    message.obj = bundle;
                    dispatcher.sendMessage(message);
                }
            }
        })).build();
        RequestUtils.enqueue(mOkHttpClient, request, listener);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Message(android.os.Message) Bundle(android.os.Bundle) Request(okhttp3.Request) ProgressRequestListener(io.chelizi.amokhttp.upload.ProgressRequestListener) ProgressRequestBody(io.chelizi.amokhttp.upload.ProgressRequestBody) ProgressRequestBody(io.chelizi.amokhttp.upload.ProgressRequestBody) RequestBody(okhttp3.RequestBody)

Example 87 with RequestBody

use of okhttp3.RequestBody in project amhttp by Eddieyuan123.

the class RequestBodyFactoryImpl method buildRequestBody.

@Override
public RequestBody buildRequestBody(File file, String fileName, HashMap<String, String> params) {
    MultipartBody.Builder builder = new MultipartBody.Builder();
    if (params == null) {
        throw new NullPointerException("requestBodyFactory build params is null");
    } else {
        RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), file);
        try {
            if (params.size() > 0) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    builder.addFormDataPart(entry.getKey(), entry.getValue());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        builder.setType(MultipartBody.FORM);
        builder.addFormDataPart("file", fileName, fileBody);
    }
    return builder.build();
}
Also used : MultipartBody(okhttp3.MultipartBody) Map(java.util.Map) HashMap(java.util.HashMap) RequestBody(okhttp3.RequestBody)

Example 88 with RequestBody

use of okhttp3.RequestBody in project BookReader by JustWayward.

the class LoggingInterceptor 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(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("");
            logger.log(buffer.readString(charset));
            logger.log("--> END " + request.method() + " (" + requestBody.contentLength() + "-byte body)");
        }
    }
    long startNs = System.nanoTime();
    Response response = chain.proceed(request);
    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 || !HttpEngine.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 (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) Headers(okhttp3.Headers) Request(okhttp3.Request) Connection(okhttp3.Connection) Charset(java.nio.charset.Charset) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) MediaType(okhttp3.MediaType) Protocol(okhttp3.Protocol) RequestBody(okhttp3.RequestBody) BufferedSource(okio.BufferedSource)

Example 89 with RequestBody

use of okhttp3.RequestBody in project spring-framework by spring-projects.

the class OkHttp3ClientHttpRequestFactory method buildRequest.

static Request buildRequest(HttpHeaders headers, byte[] content, URI uri, HttpMethod method) throws MalformedURLException {
    okhttp3.MediaType contentType = getContentType(headers);
    RequestBody body = (content.length > 0 || okhttp3.internal.http.HttpMethod.requiresRequestBody(method.name()) ? RequestBody.create(contentType, content) : null);
    Request.Builder builder = new Request.Builder().url(uri.toURL()).method(method.name(), body);
    for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
        String headerName = entry.getKey();
        for (String headerValue : entry.getValue()) {
            builder.addHeader(headerName, headerValue);
        }
    }
    return builder.build();
}
Also used : Request(okhttp3.Request) List(java.util.List) Map(java.util.Map) RequestBody(okhttp3.RequestBody)

Example 90 with RequestBody

use of okhttp3.RequestBody in project realm-java by realm.

the class OkHttpAuthenticationServer method logout.

private LogoutResponse logout(URL logoutUrl, String requestBody) throws Exception {
    Request request = new Request.Builder().url(logoutUrl).addHeader("Content-Type", "application/json").addHeader("Accept", "application/json").post(RequestBody.create(JSON, requestBody)).build();
    Call call = client.newCall(request);
    Response response = call.execute();
    return LogoutResponse.from(response);
}
Also used : Response(okhttp3.Response) Call(okhttp3.Call) Request(okhttp3.Request)

Aggregations

RequestBody (okhttp3.RequestBody)178 Request (okhttp3.Request)141 IOException (java.io.IOException)75 Response (okhttp3.Response)74 Test (org.junit.Test)53 ResponseBody (okhttp3.ResponseBody)32 Call (okhttp3.Call)31 MultipartBody (okhttp3.MultipartBody)28 MediaType (okhttp3.MediaType)27 FormBody (okhttp3.FormBody)25 Callback (okhttp3.Callback)23 Buffer (okio.Buffer)23 MockResponse (okhttp3.mockwebserver.MockResponse)18 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)16 TestClients.clientRequest (keywhiz.TestClients.clientRequest)15 BufferedSink (okio.BufferedSink)15 Headers (okhttp3.Headers)12 HttpUrl (okhttp3.HttpUrl)11 JSONObject (org.json.JSONObject)11 Body (retrofit2.http.Body)11