Search in sources :

Example 41 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient 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 42 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient 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)

Example 43 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project Android-SDK by snabble.

the class CheckoutApi method createCheckoutInfo.

public void createCheckoutInfo(final ShoppingCart.BackendCart backendCart, final PaymentMethod[] clientAcceptedPaymentMethods, final CheckoutInfoResult checkoutInfoResult, final long timeout) {
    String checkoutUrl = project.getCheckoutUrl();
    if (checkoutUrl == null) {
        Logger.e("Could not checkout, no checkout url provided in metadata");
        checkoutInfoResult.connectionError();
        return;
    }
    final Request request = new Request.Builder().url(Snabble.getInstance().absoluteUrl(checkoutUrl)).post(RequestBody.create(JSON, GsonHolder.get().toJson(backendCart))).build();
    cancel();
    OkHttpClient okClient = okHttpClient;
    if (timeout > 0) {
        okClient = okClient.newBuilder().callTimeout(timeout, TimeUnit.MILLISECONDS).build();
    }
    call = okClient.newCall(request);
    call.enqueue(new JsonCallback<SignedCheckoutInfo, JsonObject>(SignedCheckoutInfo.class, JsonObject.class) {

        @Override
        public void success(SignedCheckoutInfo signedCheckoutInfo) {
            int price;
            if (signedCheckoutInfo.checkoutInfo.has("price") && signedCheckoutInfo.checkoutInfo.get("price").getAsJsonObject().has("price")) {
                price = signedCheckoutInfo.checkoutInfo.get("price").getAsJsonObject().get("price").getAsInt();
            } else {
                price = project.getShoppingCart().getTotalPrice();
            }
            PaymentMethodInfo[] availablePaymentMethods = signedCheckoutInfo.getAvailablePaymentMethods(clientAcceptedPaymentMethods);
            if (availablePaymentMethods != null && availablePaymentMethods.length > 0) {
                checkoutInfoResult.success(signedCheckoutInfo, price, availablePaymentMethods);
            } else {
                checkoutInfoResult.connectionError();
            }
        }

        @Override
        public void failure(JsonObject obj) {
            try {
                JsonObject error = obj.get("error").getAsJsonObject();
                String type = error.get("type").getAsString();
                switch(type) {
                    case "invalid_cart_item":
                        List<String> invalidSkus = new ArrayList<>();
                        JsonArray arr = error.get("details").getAsJsonArray();
                        for (int i = 0; i < arr.size(); i++) {
                            String sku = arr.get(0).getAsJsonObject().get("sku").getAsString();
                            invalidSkus.add(sku);
                        }
                        List<Product> invalidProducts = new ArrayList<>();
                        ShoppingCart cart = project.getShoppingCart();
                        for (int i = 0; i < cart.size(); i++) {
                            Product product = cart.get(i).getProduct();
                            if (product != null) {
                                if (invalidSkus.contains(product.getSku())) {
                                    invalidProducts.add(product);
                                }
                            }
                        }
                        Logger.e("Invalid products");
                        checkoutInfoResult.invalidProducts(invalidProducts);
                        break;
                    case "no_available_method":
                        checkoutInfoResult.noAvailablePaymentMethod();
                        break;
                    case "bad_shop_id":
                    case "shop_not_found":
                        checkoutInfoResult.noShop();
                        break;
                    case "invalid_deposit_return_voucher":
                        checkoutInfoResult.invalidDepositReturnVoucher();
                        break;
                    default:
                        checkoutInfoResult.unknownError();
                        break;
                }
            } catch (Exception e) {
                error(e);
            }
        }

        @Override
        public void error(Throwable t) {
            Logger.e("Error creating checkout info: " + t.getMessage());
            checkoutInfoResult.connectionError();
        }
    });
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) JsonArray(com.google.gson.JsonArray) ArrayList(java.util.ArrayList) List(java.util.List)

Example 44 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project jun_android by wujun728.

the class HttpManager method getHttpClient.

// httpGet/httpPost 内调用方法 <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
/**
 * @param url
 * @return
 */
private OkHttpClient getHttpClient(String url) {
    Log.i(TAG, "getHttpClient  url = " + url);
    if (StringUtil.isEmpty(url)) {
        Log.e(TAG, "getHttpClient  StringUtil.isEmpty(url) >> return null;");
        return null;
    }
    OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(15, TimeUnit.SECONDS).writeTimeout(10, TimeUnit.SECONDS).readTimeout(10, TimeUnit.SECONDS).cookieJar(new CookieJar() {

        @Override
        public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
            Map<String, String> map = new LinkedHashMap<>();
            if (cookies != null) {
                for (Cookie c : cookies) {
                    if (c != null && c.name() != null && c.value() != null) {
                        map.put(c.name(), StringUtil.get(c.value()));
                    }
                }
            }
            // default constructor not found  cookies));
            saveCookie(url == null ? null : url.host(), JSON.toJSONString(map));
        }

        @Override
        public List<Cookie> loadForRequest(HttpUrl url) {
            String host = url == null ? null : url.host();
            Map<String, String> map = host == null ? null : JSON.parseObject(getCookie(host), HashMap.class);
            List<Cookie> list = new ArrayList<>();
            Set<Map.Entry<String, String>> set = map == null ? null : map.entrySet();
            if (set != null) {
                for (Map.Entry<String, String> entry : set) {
                    if (entry != null && entry.getKey() != null && entry.getValue() != null) {
                        list.add(new Cookie.Builder().domain(host).name(entry.getKey()).value(entry.getValue()).build());
                    }
                }
            }
            return list;
        }
    });
    // 添加信任https证书,用于自签名,不需要可删除
    if (url.startsWith(StringUtil.URL_PREFIXs) && socketFactory != null) {
        builder.sslSocketFactory(socketFactory);
    }
    return builder.build();
}
Also used : Cookie(okhttp3.Cookie) OkHttpClient(okhttp3.OkHttpClient) Set(java.util.Set) HttpUrl(okhttp3.HttpUrl) ArrayList(java.util.ArrayList) List(java.util.List) CookieJar(okhttp3.CookieJar) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 45 with OkHttpClient

use of com.github.mjeanroy.junit.servers.client.impl.okhttp3.OkHttpClient in project openhab-addons by openhab.

the class TelegramHandler method dispose.

@Override
public void dispose() {
    logger.debug("Trying to dispose Telegram client");
    cancelThingOnlineStatusJob();
    OkHttpClient localClient = botLibClient;
    TelegramBot localBot = bot;
    if (localClient != null && localBot != null) {
        localBot.removeGetUpdatesListener();
        localClient.dispatcher().executorService().shutdown();
        localClient.connectionPool().evictAll();
        logger.debug("Telegram client closed");
    }
    super.dispose();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) TelegramBot(com.pengrad.telegrambot.TelegramBot)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)1944 Request (okhttp3.Request)1024 Response (okhttp3.Response)880 IOException (java.io.IOException)567 Test (org.junit.Test)365 Call (okhttp3.Call)290 RequestBody (okhttp3.RequestBody)222 Test (org.junit.jupiter.api.Test)145 Retrofit (retrofit2.Retrofit)138 File (java.io.File)132 HttpUrl (okhttp3.HttpUrl)131 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)128 Callback (okhttp3.Callback)117 JSONObject (org.json.JSONObject)110 ArrayList (java.util.ArrayList)106 ResponseBody (okhttp3.ResponseBody)105 Gson (com.google.gson.Gson)98 MediaType (okhttp3.MediaType)98 List (java.util.List)92 Map (java.util.Map)85