Search in sources :

Example 26 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project iGap-Android by KianIranian-STDG.

the class UploadHttpRequest method startOrResume.

private void startOrResume() {
    if (fileObject.fileToken == null) {
        FileLog.i(TAG, "startOrResume: " + fileObject.key);
        return;
    }
    isUploading = true;
    storeTime = 0;
    resumeRetryCount = 0;
    String url = FILE + "upload/" + fileObject.fileToken;
    SecureRandom secureRandom = new SecureRandom();
    byte[] iv = secureRandom.generateSeed(16);
    fileObject.auth = G.symmetricKeyString.getBytes();
    try (FileInputStream fileInputStream = new FileInputStream(fileObject.file);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(iv)) {
        if (fileObject.offset > 0 && isResume) {
            try {
                long skip = fileInputStream.skip(fileObject.offset);
            } catch (IOException e) {
                fileObject.offset = 0;
                FileLog.e(e);
            }
        }
        try (InputStream inputStream = new SequenceInputStream(byteArrayInputStream, new CipherInputStream(fileInputStream, getCipher(iv)))) {
            RequestBody requestBody = new UploadRequestBody(null, fileObject.offset, inputStream, new UploadRequestBody.IOnProgressListener() {

                @Override
                public void onProgress(long totalByte) {
                    if (cancelDownload.get() && isUploading) {
                        isUploading = false;
                        error(new Exception("Upload Canceled"), false);
                        return;
                    }
                    int progress = (int) ((totalByte * 100) / fileObject.file.length());
                    if (fileObject.progress < progress) {
                        fileObject.progress = progress;
                        FileLog.i(TAG, fileObject.fileToken + " progress -> " + fileObject.progress + " bytes -> " + totalByte);
                        AndroidUtils.globalQueue.postRunnable(() -> {
                            if (delegate != null) {
                                delegate.onUploadProgress(fileObject);
                            }
                        });
                        if (storeTime >= 3) {
                            storeTime = 0;
                            preferences.edit().putLong("offset_" + md5Key, totalByte).putString("token_" + md5Key, fileObject.fileToken).putInt("progress_" + md5Key, fileObject.progress).apply();
                        }
                        storeTime++;
                    }
                }

                @Override
                public void onError(Exception e) {
                    FileLog.i(TAG, "Error from stream " + e.getMessage());
                }
            });
            Request request = new Request.Builder().url(url).post(requestBody).addHeader("Authorization", TokenContainer.getInstance().getToken()).build();
            requestCall = client.newCall(request);
            AndroidUtils.globalQueue.postRunnable(() -> {
                // FIXME: 10/12/2020 remove to SendMessageUtil
                if (fileObject.message != null) {
                    HelperSetAction.setActionFiles(fileObject.message.getRoomId(), fileObject.messageId, HelperSetAction.getAction(fileObject.messageType), fileObject.roomType);
                }
            });
            Response response = requestCall.execute();
            if (response.isSuccessful() && response.body() != null) {
                preferences.edit().remove("offset_" + md5Key).remove("token_" + md5Key).remove("progress_" + md5Key).apply();
                AndroidUtils.globalQueue.postRunnable(() -> {
                    HelperSetAction.sendCancel(fileObject.messageId);
                    if (delegate != null) {
                        delegate.onUploadFinish(fileObject);
                    }
                });
            } else if (response.body() != null) {
                if (response.code() >= 500 && response.code() < 600) {
                    preferences.edit().remove("offset_" + md5Key).remove("token_" + md5Key).remove("progress_" + md5Key).apply();
                }
                error(new Exception(response.body().string()), false);
            }
        } catch (Exception e) {
            error(e, false);
        }
    } catch (FileNotFoundException e) {
        FileLog.e(e);
    } catch (IOException e) {
        FileLog.e(e);
    }
}
Also used : CipherInputStream(javax.crypto.CipherInputStream) CipherInputStream(javax.crypto.CipherInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SequenceInputStream(java.io.SequenceInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Request(okhttp3.Request) FileNotFoundException(java.io.FileNotFoundException) SecureRandom(java.security.SecureRandom) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) JSONException(org.json.JSONException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) Response(okhttp3.Response) SequenceInputStream(java.io.SequenceInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) UploadRequestBody(net.iGap.helper.upload.UploadRequestBody) RequestBody(okhttp3.RequestBody) UploadRequestBody(net.iGap.helper.upload.UploadRequestBody)

Example 27 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project spring-framework-debug by Joker-5.

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);
    headers.forEach((headerName, headerValues) -> {
        for (String headerValue : headerValues) {
            builder.addHeader(headerName, headerValue);
        }
    });
    return builder.build();
}
Also used : Request(okhttp3.Request) RequestBody(okhttp3.RequestBody)

Example 28 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project media by androidx.

the class OkHttpDataSource method makeRequest.

/**
 * Establishes a connection.
 */
private Request makeRequest(DataSpec dataSpec) throws HttpDataSourceException {
    long position = dataSpec.position;
    long length = dataSpec.length;
    @Nullable HttpUrl url = HttpUrl.parse(dataSpec.uri.toString());
    if (url == null) {
        throw new HttpDataSourceException("Malformed URL", dataSpec, PlaybackException.ERROR_CODE_FAILED_RUNTIME_CHECK, HttpDataSourceException.TYPE_OPEN);
    }
    Request.Builder builder = new Request.Builder().url(url);
    if (cacheControl != null) {
        builder.cacheControl(cacheControl);
    }
    Map<String, String> headers = new HashMap<>();
    if (defaultRequestProperties != null) {
        headers.putAll(defaultRequestProperties.getSnapshot());
    }
    headers.putAll(requestProperties.getSnapshot());
    headers.putAll(dataSpec.httpRequestHeaders);
    for (Map.Entry<String, String> header : headers.entrySet()) {
        builder.header(header.getKey(), header.getValue());
    }
    @Nullable String rangeHeader = buildRangeRequestHeader(position, length);
    if (rangeHeader != null) {
        builder.addHeader(HttpHeaders.RANGE, rangeHeader);
    }
    if (userAgent != null) {
        builder.addHeader(HttpHeaders.USER_AGENT, userAgent);
    }
    if (!dataSpec.isFlagSet(DataSpec.FLAG_ALLOW_GZIP)) {
        builder.addHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
    }
    @Nullable RequestBody requestBody = null;
    if (dataSpec.httpBody != null) {
        requestBody = RequestBody.create(null, dataSpec.httpBody);
    } else if (dataSpec.httpMethod == DataSpec.HTTP_METHOD_POST) {
        // OkHttp requires a non-null body for POST requests.
        requestBody = RequestBody.create(null, Util.EMPTY_BYTE_ARRAY);
    }
    builder.method(dataSpec.getHttpMethodString(), requestBody);
    return builder.build();
}
Also used : HashMap(java.util.HashMap) Request(okhttp3.Request) HashMap(java.util.HashMap) Map(java.util.Map) Nullable(androidx.annotation.Nullable) HttpUrl(okhttp3.HttpUrl) RequestBody(okhttp3.RequestBody)

Example 29 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project forest by dromara.

the class OkHttp3Executor method setLogBody.

protected void setLogBody(RequestLogMessage message, Request okRequest) {
    RequestBody requestBody = okRequest.body();
    LogBodyMessage logBodyMessage = new OkHttp3LogBodyMessage(requestBody);
    message.setBody(logBodyMessage);
}
Also used : OkHttp3LogBodyMessage(com.dtflys.forest.backend.okhttp3.logging.OkHttp3LogBodyMessage) OkHttp3LogBodyMessage(com.dtflys.forest.backend.okhttp3.logging.OkHttp3LogBodyMessage) LogBodyMessage(com.dtflys.forest.logging.LogBodyMessage) RequestBody(okhttp3.RequestBody)

Example 30 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project forest by dromara.

the class OkHttp3LogBodyMessage method getBodyString.

@Override
public String getBodyString() {
    if (requestBody == null) {
        return null;
    }
    MediaType mediaType = requestBody.contentType();
    if (mediaType == null) {
        return getLogContentForStringBody(this.requestBody);
    }
    ContentType contentType = new ContentType(mediaType.toString());
    if (contentType.isMultipart()) {
        MultipartBody multipartBody = (MultipartBody) requestBody;
        String boundary = multipartBody.boundary();
        Long contentLength = null;
        try {
            contentLength = multipartBody.contentLength();
        } catch (IOException e) {
        }
        StringBuilder builder = new StringBuilder();
        builder.append("[").append("boundary=").append(boundary);
        if (contentLength != null) {
            builder.append("; length=").append(contentLength);
        }
        builder.append("] parts:");
        List<MultipartBody.Part> parts = multipartBody.parts();
        for (MultipartBody.Part part : parts) {
            RequestBody partBody = part.body();
            List<String> disposition = part.headers().values("Content-Disposition");
            builder.append("\n             -- [").append(disposition.get(0));
            MediaType partMediaType = partBody.contentType();
            if (partMediaType == null) {
                builder.append("; content-type=\"").append(partBody.contentType()).append("\"");
                builder.append("; value=\"").append(getLogContentForStringBody(partBody)).append("\"]");
            } else {
                Long length = null;
                try {
                    length = partBody.contentLength();
                } catch (IOException e) {
                }
                if (length != null) {
                    builder.append("; length=").append(length);
                }
                builder.append("; content-type=\"").append(partBody.contentType()).append("\"");
                builder.append("]");
            }
        }
        return builder.toString();
    } else if (contentType.isBinary()) {
        try {
            return "[Binary length=" + requestBody.contentLength() + "]";
        } catch (IOException e) {
            throw new ForestRuntimeException(e);
        }
    }
    return getLogContentForStringBody(this.requestBody);
}
Also used : ContentType(com.dtflys.forest.backend.ContentType) ForestRuntimeException(com.dtflys.forest.exceptions.ForestRuntimeException) IOException(java.io.IOException) MultipartBody(okhttp3.MultipartBody) MediaType(okhttp3.MediaType) RequestBody(okhttp3.RequestBody)

Aggregations

RequestBody (okhttp3.RequestBody)1358 Request (okhttp3.Request)785 Response (okhttp3.Response)598 IOException (java.io.IOException)420 Test (org.junit.Test)235 OkHttpClient (okhttp3.OkHttpClient)216 MultipartBody (okhttp3.MultipartBody)213 MediaType (okhttp3.MediaType)204 Call (okhttp3.Call)198 JSONObject (org.json.JSONObject)183 ResponseBody (okhttp3.ResponseBody)177 Callback (okhttp3.Callback)115 FormBody (okhttp3.FormBody)106 Buffer (okio.Buffer)98 File (java.io.File)92 Map (java.util.Map)90 JsonObject (io.vertx.core.json.JsonObject)89 Headers (okhttp3.Headers)88 HashMap (java.util.HashMap)83 HttpUrl (okhttp3.HttpUrl)80