Search in sources :

Example 16 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project the-blue-alliance-android by the-blue-alliance.

the class ImgurSuggestionService method onHandleIntent.

@Override
protected void onHandleIntent(Intent intent) {
    TbaLogger.d("IMGUR SERVICE START");
    String filepath = intent.getStringExtra(EXTRA_FILEPATH);
    String title = intent.getStringExtra(EXTRA_TITLE);
    String description = intent.getStringExtra(EXTRA_DESCRIPTION);
    String teamKey = intent.getStringExtra(EXTRA_TEAMKEY);
    int year = intent.getIntExtra(EXTRA_YEAR, 0);
    ImgurUploadNotification notification = new ImgurUploadNotification(getApplicationContext());
    notification.onUploadStarting();
    boolean successful = true;
    // Get a wake lock so any long uploads will not be interrupted
    PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
    PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
    wakeLock.acquire();
    // TODO should we catch each exception individually and handle them better (e.g. retyr?)
    try {
        String authToken = getAuthHeader();
        File file = new File(filepath);
        RequestBody body = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        RequestBody titlePart = RequestBody.create(MediaType.parse("text/plain"), title);
        RequestBody descPart = RequestBody.create(MediaType.parse("text/plain"), description);
        Response<UploadResponse> response = mImgurApi.uploadImage(authToken, titlePart, descPart, body).execute();
        if (response != null && response.isSuccessful()) {
            UploadResponse uploadResponse = response.body();
            TbaLogger.d("Uploaded imgur image: " + uploadResponse.data.link);
            String link = uploadResponse.data.link;
            String deletehash = uploadResponse.data.deletehash;
            TbaLogger.d("Imgur link: " + link);
            // Do suggestion
            String authHeader = mGceAuthController.getAuthHeader();
            ModelsMobileApiMessagesMediaSuggestionMessage message = buildSuggestionMessage(teamKey, year, link, deletehash);
            Response<ModelsMobileApiMessagesBaseResponse> suggestionResponse = mTeamMediaApi.suggestion(authHeader, message).execute();
            if (suggestionResponse != null && suggestionResponse.isSuccessful()) {
            // Yay, everything worked!
            } else {
                // Crap
                // TODO handle this
                successful = false;
            }
        } else {
            TbaLogger.e("Error uploading imgur image\n" + response.code() + " " + response.message());
            successful = false;
        }
    } catch (Exception e) {
        // Something broke
        successful = false;
        e.printStackTrace();
    } finally {
        if (successful) {
            notification.onUploadSuccess();
        } else {
            notification.onUploadFailure();
        }
        // Delete the temp cached image
        new File(filepath).delete();
        wakeLock.release();
    }
}
Also used : ModelsMobileApiMessagesMediaSuggestionMessage(com.appspot.tbatv_prod_hrd.model.ModelsMobileApiMessagesMediaSuggestionMessage) AndroidEntryPoint(dagger.hilt.android.AndroidEntryPoint) PowerManager(android.os.PowerManager) UploadResponse(com.thebluealliance.imgur.responses.UploadResponse) ModelsMobileApiMessagesBaseResponse(com.appspot.tbatv_prod_hrd.model.ModelsMobileApiMessagesBaseResponse) File(java.io.File) RequestBody(okhttp3.RequestBody)

Example 17 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project AnkiChinaAndroid by ankichinateam.

the class AbstractFlashcardViewer method consumeOnlineVoiceInfo.

private void consumeOnlineVoiceInfo(String token) {
    RequestBody formBody = new FormBody.Builder().build();
    OKHttpUtil.post(Consts.ANKI_CHINA_BASE + Consts.API_VERSION + "users/consumeVoice", formBody, token, "", new OKHttpUtil.MyCallBack() {

        @Override
        public void onFailure(Call call, IOException e) {
        }

        @Override
        public void onResponse(Call call, String token, Object arg1, Response response) {
            if (response.isSuccessful()) {
                try {
                    final org.json.JSONObject object = new org.json.JSONObject(response.body().string());
                    final org.json.JSONObject item = object.getJSONObject("data");
                    mFreeOnlineEngineCount = item.getInt("total");
                    // mFreeOnlineEngineCount = 100;
                    preferences.edit().putInt(Consts.KEY_REST_ONLINE_SPEAK_COUNT, mFreeOnlineEngineCount).apply();
                    Timber.e("consume voice successfully, current total is %d", mFreeOnlineEngineCount);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Timber.e("consume voice failed, error code %d", response.code());
            }
        }
    });
}
Also used : Call(okhttp3.Call) OKHttpUtil(com.ichi2.utils.OKHttpUtil) FormBody(okhttp3.FormBody) IOException(java.io.IOException) JSONException(com.ichi2.utils.JSONException) IOException(java.io.IOException) ActivityNotFoundException(android.content.ActivityNotFoundException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) WebResourceResponse(android.webkit.WebResourceResponse) Response(okhttp3.Response) JSONObject(com.ichi2.utils.JSONObject) JSONObject(com.ichi2.utils.JSONObject) RequestBody(okhttp3.RequestBody)

Example 18 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project spring-boot-examples by tedburner.

the class OkHttpServiceImpl method POST.

@Override
public byte[] POST(String url, String jsonBody) throws HttpException, IOException {
    RequestBody body = RequestBody.create(MEDIA_JSON, jsonBody);
    Request request = new Request.Builder().url(url).post(body).build();
    Response response = ReqExecute(request);
    if (!response.isSuccessful()) {
        throw new HttpException(response, "exception code:" + response.code());
    }
    return response.body().bytes();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) HttpException(com.springboot.sample.util.okhttp.HttpException) RequestBody(okhttp3.RequestBody)

Example 19 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project Android-SDK by snabble.

the class Users method setBirthday.

public void setBirthday(Date birthday, final UpdateUserCallback updateUserCallback) {
    final Snabble snabble = Snabble.getInstance();
    String url = snabble.getUsersUrl();
    AppUser appUser = snabble.getUserPreferences().getAppUser();
    if (appUser != null && url != null) {
        Request updateBirthdayRequest = new Request();
        updateBirthdayRequest.id = appUser.id;
        updateBirthdayRequest.dayOfBirth = simpleDateFormat.format(birthday);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonHolder.get().toJson(updateBirthdayRequest));
        okhttp3.Request request = new okhttp3.Request.Builder().patch(requestBody).url(url.replace("{appUserID}", appUser.id)).build();
        OkHttpClient okHttpClient = snabble.getProjects().get(0).getOkHttpClient();
        updateBirthdayCall = okHttpClient.newCall(request);
        updateBirthdayCall.enqueue(new Callback() {

            @Override
            public void onFailure(Call call, IOException e) {
                updateBirthdayCall = null;
                updateUserCallback.failure();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) {
                if (response.isSuccessful()) {
                    updateBirthdayCall = null;
                    updateUserCallback.success();
                } else {
                    updateBirthdayCall = null;
                    updateUserCallback.failure();
                }
            }
        });
    } else {
        updateUserCallback.failure();
    }
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) AppUser(io.snabble.sdk.auth.AppUser) IOException(java.io.IOException) SimpleJsonCallback(io.snabble.sdk.utils.SimpleJsonCallback) Callback(okhttp3.Callback) RequestBody(okhttp3.RequestBody)

Example 20 with RequestBody

use of com.reprezen.kaizen.oasparser.model3.RequestBody in project Android-SDK by snabble.

the class Users method postConsentVersion.

private void postConsentVersion() {
    final Snabble snabble = Snabble.getInstance();
    String url = snabble.getConsentUrl();
    AppUser appUser = userPreferences.getAppUser();
    if (appUser == null || url == null) {
        return;
    }
    String version = userPreferences.getConsentVersion();
    UpdateConsentRequest updateBirthdayRequest = new UpdateConsentRequest();
    updateBirthdayRequest.version = version;
    RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), GsonHolder.get().toJson(updateBirthdayRequest));
    okhttp3.Request request = new okhttp3.Request.Builder().post(requestBody).url(url.replace("{appUserID}", appUser.id)).build();
    userPreferences.setConsentStatus(UserPreferences.ConsentStatus.TRANSMITTING);
    OkHttpClient okHttpClient = snabble.getProjects().get(0).getOkHttpClient();
    postConsentCall = okHttpClient.newCall(request);
    postConsentCall.enqueue(new Callback() {

        @Override
        public void onFailure(Call call, IOException e) {
            postConsentCall = null;
            userPreferences.setConsentStatus(UserPreferences.ConsentStatus.TRANSMIT_FAILED);
        }

        @Override
        public void onResponse(Call call, okhttp3.Response response) {
            if (response.isSuccessful()) {
                postConsentCall = null;
                userPreferences.setConsentStatus(UserPreferences.ConsentStatus.ACCEPTED);
            } else {
                postConsentCall = null;
                if (response.code() == 400) {
                    userPreferences.setConsentStatus(UserPreferences.ConsentStatus.ACCEPTED);
                } else {
                    userPreferences.setConsentStatus(UserPreferences.ConsentStatus.TRANSMIT_FAILED);
                }
            }
        }
    });
}
Also used : Call(okhttp3.Call) OkHttpClient(okhttp3.OkHttpClient) AppUser(io.snabble.sdk.auth.AppUser) IOException(java.io.IOException) SimpleJsonCallback(io.snabble.sdk.utils.SimpleJsonCallback) Callback(okhttp3.Callback) 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