Search in sources :

Example 61 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project odysee-android by OdyseeTeam.

the class TwitterRequestTokenTask method doInBackground.

public String doInBackground(Void... params) {
    try {
        OAuthHmacSigner signer = new OAuthHmacSigner();
        signer.clientSharedSecret = new String(Base64.decode(consumerSecret, Base64.NO_WRAP), StandardCharsets.UTF_8.name());
        OAuthParameters oauthParams = new OAuthParameters();
        oauthParams.callback = "https://lbry.tv";
        oauthParams.consumerKey = new String(Base64.decode(consumerKey, Base64.NO_WRAP), StandardCharsets.UTF_8.name());
        oauthParams.signatureMethod = "HMAC-SHA-1";
        oauthParams.signer = signer;
        oauthParams.computeNonce();
        oauthParams.computeTimestamp();
        oauthParams.computeSignature("POST", new GenericUrl(ENDPOINT));
        RequestBody body = RequestBody.create(new byte[0]);
        Request request = new Request.Builder().url(ENDPOINT).addHeader("Authorization", oauthParams.getAuthorizationHeader()).post(body).build();
        OkHttpClient client = new OkHttpClient.Builder().build();
        Response response = client.newCall(request).execute();
        return response.body().string();
    } catch (Exception ex) {
        error = ex;
        return null;
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) OAuthHmacSigner(com.google.api.client.auth.oauth.OAuthHmacSigner) OAuthParameters(com.google.api.client.auth.oauth.OAuthParameters) Request(okhttp3.Request) GenericUrl(com.google.api.client.http.GenericUrl) RequestBody(okhttp3.RequestBody)

Example 62 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project odysee-android by OdyseeTeam.

the class BufferEventTask method doInBackground.

protected Void doInBackground(Void... params) {
    JSONObject requestBody = new JSONObject();
    JSONObject data = new JSONObject();
    try {
        data.put("url", streamUrl);
        data.put("position", streamPosition);
        data.put("stream_duration", streamDuration);
        // data.put("duration", bufferDuration);
        requestBody.put("device", "android");
        requestBody.put("type", "buffering");
        requestBody.put("client", userIdHash);
        requestBody.put("data", data);
        RequestBody body = RequestBody.create(requestBody.toString(), Helper.JSON_MEDIA_TYPE);
        Request request = new Request.Builder().url(ENDPOINT).post(body).build();
        OkHttpClient client = new OkHttpClient.Builder().writeTimeout(60, TimeUnit.SECONDS).readTimeout(60, TimeUnit.SECONDS).build();
        Response response = client.newCall(request).execute();
        ResponseBody resBody = response.body();
        String responseString = "";
        if (resBody != null) {
            responseString = resBody.string();
        }
        response.close();
        Log.d(TAG, String.format("buffer event sent: %s", responseString));
    } catch (Exception ex) {
        // we don't want to fail if a buffer event fails to register
        Log.d(TAG, String.format("buffer event log failed: %s", ex.getMessage()), ex);
    }
    return null;
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) RequestBody(okhttp3.RequestBody) ResponseBody(okhttp3.ResponseBody)

Example 63 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project odysee-android by OdyseeTeam.

the class UploadImageTask method doInBackground.

protected String doInBackground(Void... params) {
    String thumbnailUrl = null;
    try {
        File file = new File(filePath);
        String fileName = file.getName();
        int dotIndex = fileName.lastIndexOf('.');
        String extension = "jpg";
        if (dotIndex > -1) {
            extension = fileName.substring(dotIndex + 1);
        }
        String fileType = String.format("image/%s", extension);
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("name", Helper.makeid(24)).addFormDataPart("file", fileName, RequestBody.create(file, MediaType.parse(fileType))).build();
        Request request = new Request.Builder().url("https://spee.ch/api/claim/publish").post(body).build();
        OkHttpClient client = new OkHttpClient.Builder().writeTimeout(300, TimeUnit.SECONDS).readTimeout(300, TimeUnit.SECONDS).build();
        Response response = client.newCall(request).execute();
        JSONObject json = new JSONObject(response.body().string());
        if (json.has("success") && Helper.getJSONBoolean("success", false, json)) {
            JSONObject data = json.getJSONObject("data");
            String url = Helper.getJSONString("url", null, data);
            if (Helper.isNullOrEmpty(url)) {
                throw new LbryResponseException("Invalid thumbnail url returned after upload.");
            }
            thumbnailUrl = String.format("%s.%s", url, extension);
        } else if (json.has("error") || json.has("message")) {
            JSONObject error = Helper.getJSONObject("error", json);
            String message = null;
            if (error != null) {
                message = Helper.getJSONString("message", null, error);
            }
            if (Helper.isNullOrEmpty(message)) {
                message = Helper.getJSONString("message", null, json);
            }
            throw new LbryResponseException(Helper.isNullOrEmpty(message) ? "The image failed to upload." : message);
        }
    } catch (IOException | JSONException | LbryResponseException ex) {
        error = ex;
    }
    return thumbnailUrl;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JSONException(org.json.JSONException) LbryResponseException(com.odysee.app.exceptions.LbryResponseException) IOException(java.io.IOException) Response(okhttp3.Response) JSONObject(org.json.JSONObject) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 64 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project pod-chat-android-sdk by FanapSoft.

the class PodUploader method uploadImageToPodSpace.

private static Subscription uploadImageToPodSpace(String uniqueId, String threadHashCode, String fileServer, String token, int tokenIssuer, String xC, String yC, String hC, String wC, IPodUploadFileToPodSpace listener, String mimeType, File file, long fileSize) throws FileNotFoundException {
    int width = 0;
    int height = 0;
    String nWidth = "0";
    String nHeight = "0";
    try {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        width = options.outWidth;
        height = options.outHeight;
        nWidth = !Util.isNullOrEmpty(wC) ? wC : String.valueOf(width);
        nHeight = !Util.isNullOrEmpty(hC) ? hC : String.valueOf(height);
    } catch (Exception e) {
        throw new FileNotFoundException("Invalid image!");
    }
    listener.onUploadStarted(mimeType, file, fileSize);
    RetrofitHelperFileServer retrofitHelperFileServer = new RetrofitHelperFileServer(fileServer);
    FileApi fileApi = retrofitHelperFileServer.getService(FileApi.class);
    RequestBody namePart = RequestBody.create(MediaType.parse("multipart/form-data"), file.getName());
    RequestBody hashGroupPart = RequestBody.create(MediaType.parse("multipart/form-data"), threadHashCode);
    RequestBody xCPart = RequestBody.create(MediaType.parse("multipart/form-data"), !Util.isNullOrEmpty(xC) ? xC : "0");
    RequestBody yCPart = RequestBody.create(MediaType.parse("multipart/form-data"), !Util.isNullOrEmpty(yC) ? yC : "0");
    RequestBody hCPart = RequestBody.create(MediaType.parse("multipart/form-data"), nWidth);
    RequestBody wCPart = RequestBody.create(MediaType.parse("multipart/form-data"), nHeight);
    ProgressRequestBody requestFile = new ProgressRequestBody(file, mimeType, uniqueId, new ProgressRequestBody.UploadCallbacks() {

        @Override
        public void onProgress(String uniqueId, int progress, int totalBytesSent, int totalBytesToSend) {
            if (progress < 95)
                listener.onProgressUpdate(progress, totalBytesSent, totalBytesToSend);
        }
    });
    MultipartBody.Part filePart = MultipartBody.Part.createFormData("file", file.getName(), requestFile);
    Observable<Response<UploadToPodSpaceResponse>> uploadObservable = fileApi.uploadImageToPodSpace(filePart, token, tokenIssuer, namePart, hashGroupPart, xCPart, yCPart, wCPart, hCPart);
    int finalWidth = width;
    int finalHeight = height;
    String finalNWidth = nWidth;
    String finalNHeight = nHeight;
    return uploadObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).doOnError(error -> listener.onFailure(error.getMessage(), error)).subscribe(response -> {
        if (response.isSuccessful() && response.body() != null) {
            if (response.body().isHasError()) {
                listener.onFailure(response.body().getMessage(), new PodChatException(response.body().getMessage(), uniqueId, token));
                return;
            }
            listener.onProgressUpdate(100, (int) fileSize, 0);
            listener.onSuccess(response.body().getUploadToPodSpaceResult(), file, mimeType, fileSize, finalWidth, finalHeight, Integer.parseInt(finalNWidth), Integer.parseInt(finalNHeight));
        } else {
            try {
                if (response.errorBody() != null) {
                    listener.onFailure(response.errorBody().string(), new PodChatException(response.errorBody().string(), uniqueId, token));
                } else {
                    listener.onFailure(response.message(), new PodChatException(response.message(), uniqueId, token));
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }, error -> listener.onFailure(error.getMessage(), error));
}
Also used : Context(android.content.Context) PodChatException(com.fanap.podchat.util.PodChatException) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) Uri(android.net.Uri) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) BitmapFactory(android.graphics.BitmapFactory) NonNull(android.support.annotation.NonNull) ResultFile(com.fanap.podchat.model.ResultFile) Response(retrofit2.Response) FileUpload(com.fanap.podchat.mainmodel.FileUpload) ChatConstant(com.fanap.podchat.util.ChatConstant) ChatResponse(com.fanap.podchat.model.ChatResponse) RequestBody(okhttp3.RequestBody) Observable(rx.Observable) Schedulers(rx.schedulers.Schedulers) FilePick(com.fanap.podchat.util.FilePick) Log(android.util.Log) MediaType(okhttp3.MediaType) TAG(com.fanap.podchat.chat.Chat.TAG) IOException(java.io.IOException) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) Util(com.fanap.podchat.util.Util) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ResultImageFile(com.fanap.podchat.model.ResultImageFile) FileImageUpload(com.fanap.podchat.model.FileImageUpload) MultipartBody(okhttp3.MultipartBody) Subscription(rx.Subscription) UploadingQueueCache(com.fanap.podchat.cachemodel.queue.UploadingQueueCache) FileUtils(com.fanap.podchat.util.FileUtils) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) PodChatException(com.fanap.podchat.util.PodChatException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) Response(retrofit2.Response) ChatResponse(com.fanap.podchat.model.ChatResponse) PodChatException(com.fanap.podchat.util.PodChatException) MultipartBody(okhttp3.MultipartBody) BitmapFactory(android.graphics.BitmapFactory) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) RequestBody(okhttp3.RequestBody) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody)

Example 65 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project pod-chat-android-sdk by FanapSoft.

the class PodUploader method uploadImageToChatServer.

public static Subscription uploadImageToChatServer(String uniqueId, @NonNull Uri fileUri, Context context, String fileServer, String token, int tokenIssuer, IPodUploadImage listener) throws Exception {
    if (fileUri.getPath() == null)
        throw new NullPointerException("Invalid file uri!");
    String mimeType = FileUtils.getMimeType(fileUri, context);
    String path = FilePick.getSmartFilePath(context, fileUri);
    if (path == null)
        throw new NullPointerException("Invalid path!");
    File file = new File(path);
    if (!file.exists() || !file.isFile())
        throw new FileNotFoundException("Invalid file!");
    long fileSize = 0;
    try {
        fileSize = file.length();
    } catch (Exception x) {
        Log.e(TAG, "File length exception: " + x.getMessage());
    }
    listener.onUploadStarted(mimeType, file, fileSize);
    RetrofitHelperFileServer retrofitHelperFileServer = new RetrofitHelperFileServer(fileServer);
    FileApi fileApi = retrofitHelperFileServer.getService(FileApi.class);
    RequestBody namePart = RequestBody.create(MediaType.parse("multipart/form-data"), file.getName());
    ProgressRequestBody requestFile = new ProgressRequestBody(file, mimeType, uniqueId, new ProgressRequestBody.UploadCallbacks() {

        @Override
        public void onProgress(String uniqueId, int progress, int totalBytesSent, int totalBytesToSend) {
            listener.onProgressUpdate(progress, totalBytesSent, totalBytesToSend);
        }
    });
    MultipartBody.Part filePart = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
    Observable<Response<FileImageUpload>> uploadObservable = fileApi.sendImageFile(filePart, token, tokenIssuer, namePart);
    long finalFileSize = fileSize;
    return uploadObservable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).doOnError(error -> listener.onFailure(uniqueId + " - " + error.getMessage(), error)).subscribe(response -> {
        if (response.isSuccessful() && response.body() != null) {
            if (response.body().isHasError()) {
                listener.onFailure(uniqueId + " - " + response.body().getMessage() + " - " + response.body().getReferenceNumber(), new PodChatException(uniqueId + " - " + response.body().getMessage() + " - " + response.body().getReferenceNumber(), uniqueId, token));
            } else {
                listener.onSuccess(response.body(), file, mimeType, finalFileSize);
            }
        } else {
            if (response.body() != null) {
                listener.onFailure(uniqueId + " - " + response.body().getMessage() + " - " + response.body().getReferenceNumber(), new PodChatException(uniqueId + " - " + response.body().getMessage() + " - " + response.body().getReferenceNumber(), uniqueId, token));
            } else {
                listener.onFailure(uniqueId + " - " + response.message(), new PodChatException(uniqueId + " - " + response.message(), uniqueId, token));
            }
        }
    });
}
Also used : Context(android.content.Context) PodChatException(com.fanap.podchat.util.PodChatException) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) Uri(android.net.Uri) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) BitmapFactory(android.graphics.BitmapFactory) NonNull(android.support.annotation.NonNull) ResultFile(com.fanap.podchat.model.ResultFile) Response(retrofit2.Response) FileUpload(com.fanap.podchat.mainmodel.FileUpload) ChatConstant(com.fanap.podchat.util.ChatConstant) ChatResponse(com.fanap.podchat.model.ChatResponse) RequestBody(okhttp3.RequestBody) Observable(rx.Observable) Schedulers(rx.schedulers.Schedulers) FilePick(com.fanap.podchat.util.FilePick) Log(android.util.Log) MediaType(okhttp3.MediaType) TAG(com.fanap.podchat.chat.Chat.TAG) IOException(java.io.IOException) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) Util(com.fanap.podchat.util.Util) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) ResultImageFile(com.fanap.podchat.model.ResultImageFile) FileImageUpload(com.fanap.podchat.model.FileImageUpload) MultipartBody(okhttp3.MultipartBody) Subscription(rx.Subscription) UploadingQueueCache(com.fanap.podchat.cachemodel.queue.UploadingQueueCache) FileUtils(com.fanap.podchat.util.FileUtils) FileNotFoundException(java.io.FileNotFoundException) PodChatException(com.fanap.podchat.util.PodChatException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) RetrofitHelperFileServer(com.fanap.podchat.networking.retrofithelper.RetrofitHelperFileServer) Response(retrofit2.Response) ChatResponse(com.fanap.podchat.model.ChatResponse) PodChatException(com.fanap.podchat.util.PodChatException) MultipartBody(okhttp3.MultipartBody) ResultFile(com.fanap.podchat.model.ResultFile) File(java.io.File) ResultImageFile(com.fanap.podchat.model.ResultImageFile) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody) FileApi(com.fanap.podchat.networking.api.FileApi) RequestBody(okhttp3.RequestBody) ProgressRequestBody(com.fanap.podchat.networking.ProgressRequestBody)

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