Example usage for com.squareup.okhttp Call enqueue

List of usage examples for com.squareup.okhttp Call enqueue

Introduction

In this page you can find the example usage for com.squareup.okhttp Call enqueue.

Prototype

public void enqueue(Callback responseCallback) 

Source Link

Document

Schedules the request to be executed at some point in the future.

Usage

From source file:com.liferay.mobile.android.http.client.OkHttpClientImpl.java

License:Open Source License

protected void sendAsync(Call call, final Callback callback) {
    call.enqueue(new com.squareup.okhttp.Callback() {

        @Override/*  w w  w  . j av  a 2s.c o  m*/
        public void onFailure(com.squareup.okhttp.Request request, IOException ioe) {

            callback.doFailure(ioe);
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response response) throws IOException {

            callback.inBackground(new Response(response));
        }

    });
}

From source file:com.liferay.mobile.sdk.auth.CookieSignIn.java

License:Open Source License

public static void signIn(Config config, CookieCallback callback) {
    try {//  w w w.  jav a 2  s.  co  m
        Authentication auth = config.auth();

        if (!(auth instanceof BasicAuthentication)) {
            throw new Exception(
                    "Can't sign in if authentication implementation is not " + "BasicAuthentication");
        }

        OkHttpClient client = new OkHttpClient();

        CookieManager cookieManager = new CookieManager();

        cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL);

        client.setCookieHandler(cookieManager);
        client.setFollowRedirects(true);

        Builder builder = new Builder();

        MediaType contentType = MediaType.parse("application/x-www-form-urlencoded");

        builder.post(RequestBody.create(contentType, getBody((BasicAuthentication) auth)));

        builder.addHeader("Cookie", "COOKIE_SUPPORT=true;");
        builder.url(getLoginURL(config.server()));

        Call call = client.newCall(builder.build());

        call.enqueue(getCallback(callback, cookieManager));
    } catch (Exception e) {
        callback.onFailure(e);
    }
}

From source file:com.pangbo.android.thirdframworks.retrofit.OkHttpCall.java

License:Apache License

@Override
public void enqueue(final Callback<T> callback) {
    synchronized (this) {
        if (executed)
            throw new IllegalStateException("Already executed");
        executed = true;/*w  ww  .  jav  a 2s  . co  m*/
    }

    com.squareup.okhttp.Call rawCall;
    try {
        rawCall = createRawCall();
    } catch (Throwable t) {
        callback.onFailure(t);
        return;
    }
    if (canceled) {
        rawCall.cancel();
    }
    this.rawCall = rawCall;

    rawCall.enqueue(new com.squareup.okhttp.Callback() {
        private void callFailure(Throwable e) {
            try {
                callback.onFailure(e);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        private void callSuccess(Response<T> response) {
            try {
                callback.onResponse(response);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        @Override
        public void onFailure(Request request, IOException e) {
            callFailure(e);
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response rawResponse) {
            Response<T> response;
            try {
                response = parseResponse(rawResponse);
            } catch (Throwable e) {
                callFailure(e);
                return;
            }
            callSuccess(response);
        }
    });
}

From source file:com.rsu.nuttanun.testdrivingvlicense.ConfirmScoreActivity.java

public void clickOKConfirm(View view) {

    String urlPHP = "http://swiftcodingthai.com/toey/add_score.php";

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("id_login", loginStrings[0])
            .add("Date", dateString).add("Score", scoreString).build();
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override/*from w w w  .ja v  a  2  s  .c om*/
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

            Intent intent = new Intent(ConfirmScoreActivity.this, ScoreListView.class);
            intent.putExtra("login", loginStrings);
            startActivity(intent);
            finish();
        }
    });

}

From source file:com.rsu.nuttanun.testdrivingvlicense.ScoreListView.java

private void createListView() {

    String urlPHP = "http://swiftcodingthai.com/toey/get_score_where.php";
    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("id_login", loginStrings[0])
            .build();//from w w w . ja v a 2s .co m
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {

            String strResponse = response.body().string();
            Log.d("10AugV2", "strResponse ==>" + strResponse);

            try {

                JSONArray jsonArray = new JSONArray(strResponse);

                String[] dateStrings = new String[jsonArray.length()];
                String[] scoreStrings = new String[jsonArray.length()];

                for (int i = 0; i < jsonArray.length(); i++) {

                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    dateStrings[i] = jsonObject.getString("Date");
                    scoreStrings[i] = jsonObject.getString("Score") + " ?";

                } //for

                CoaurseAdapter coaurseAdapter = new CoaurseAdapter(ScoreListView.this, 1, dateStrings,
                        scoreStrings);
                listView.setAdapter(coaurseAdapter);

            } catch (Exception e) {
                e.printStackTrace();

            }

        } // onRespose
    });

}

From source file:com.rsu.nuttanun.testdrivingvlicense.SignUpActivity.java

private void upLoadNewUser() {

    OkHttpClient okHttpClient = new OkHttpClient();
    RequestBody requestBody = new FormEncodingBuilder().add("isAdd", "true").add("Name", nameString)
            .add("Surname", surnameString).add("Age", ageString).add("User", userString)
            .add("Password", passwordString).build();
    Request.Builder builder = new Request.Builder();
    Request request = builder.url(urlPHP).post(requestBody).build();
    Call call = okHttpClient.newCall(request);
    call.enqueue(new Callback() {
        @Override//from  w  w  w . j  av  a2s . c om
        public void onFailure(Request request, IOException e) {

        }

        @Override
        public void onResponse(Response response) throws IOException {
            finish();

        }
    });

}

From source file:com.saiyanstudio.groceryassistant.RecipeActivity.java

private void initializeData() {

    //food2fork api
    //spoonacularFridgeAPIURL = "http://food2fork.com/api/search?key=eae722f5d2be7fd8fb1a0cd6a9310dbd&q=shredded%20chicken";

    spoonacularFridgeAPIURL = "https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/findByIngredients?ingredients=";

    String ingredientListString = "";
    for (int j = 0; j < ingredientList.size(); j++) {
        ingredientListString = ingredientListString + ingredientList.get(j).toLowerCase().replace(" ", "+");
        if (j != (ingredientList.size() - 1))
            ingredientListString += "%2C";
    }/* w  w w . j  a  v  a2s . c  o  m*/

    //ingredientListString = "apples%2Cflour%2Csugar";

    spoonacularFridgeAPIURL += ingredientListString;

    spoonacularFridgeAPIURL += "&limitLicense=false&number=10&ranking=1";

    Log.i("spoonacularFridgeAPIURL", spoonacularFridgeAPIURL);

    if (isNetworkAvailable()) {

        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(spoonacularFridgeAPIURL)
                .addHeader("X-Mashape-Key", "SDS3P5crHImshhb4jdBQayo4b77hp1TvcMgjsnNMrYbE6MZuYI")
                .addHeader("Accept", "application/json").build();

        /*
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
            .url(spoonacularFridgeAPIURL)
            .build();
        */

        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
            }

            @Override
            public void onResponse(Response response) throws IOException {

                RecipeActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        recipeProgressBar.setVisibility(View.GONE);
                    }
                });

                try {
                    recipeJsonData = response.body().string();
                    Log.v("RECIPE_ACTIVITY", recipeJsonData);

                    if (response.isSuccessful()) {

                        JSONArray recipeArray = new JSONArray(recipeJsonData);
                        Log.d("RECIPE_ACTIVITY", "recipeArray.length() : " + recipeArray.length());
                        for (int i = 0; i < recipeArray.length(); i++) {
                            JSONObject recipeData = recipeArray.getJSONObject(i);
                            Log.d("RECIPE_ACTIVITY", "Recipe Name : " + recipeData.getString("title"));

                            RecipeItem recipeItem = new RecipeItem(recipeData.getString("title"),
                                    recipeData.getString("image"), recipeData.getInt("likes"),
                                    recipeData.getInt("usedIngredientCount"),
                                    recipeData.getInt("usedIngredientCount"));
                            //RecipeItem recipeItem = new RecipeItem(recipeData.getString("title"),recipeData.getString("image_url"),3,(int)recipeData.getDouble("social_rank"));

                            recipeItems.add(recipeItem);
                        }

                        RecipeActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                if (recipeItems.size() == 0)
                                    noRecipeMsg.setVisibility(View.VISIBLE);
                                else
                                    noRecipeMsg.setVisibility(View.INVISIBLE);

                                adapter.notifyDataSetChanged();
                            }
                        });
                    } else {

                        RecipeActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                noRecipeMsg.setVisibility(View.VISIBLE);
                                //Toast.makeText(RecipeActivity.this, "Sorry no recipes available", Toast.LENGTH_SHORT).show();
                            }
                        });
                    }

                } catch (IOException e) {
                    Log.e("RECIPE_ACTIVITY", "Exception caught: ", e);
                } catch (JSONException e) {
                    Log.e("RECIPE_ACTIVITY", "Exception caught: ", e);
                }

            }
        });
    } else {
        Snackbar.make(linearLayout_recipe, "Network Unavialable", Snackbar.LENGTH_INDEFINITE).show();
        //Toast.makeText(RecipeActivity.this,"Network Unavialable", Toast.LENGTH_SHORT).show();
    }
}

From source file:com.td.innovate.app.Activity.CaptureActivity.java

Call postImage(Callback callback) throws Throwable {
    RequestBody requestBody = new MultipartBuilder().type(MultipartBuilder.FORM)
            .addPart(Headers.of("Content-Disposition", "form-data; name=\"image_request[locale]\""),
                    RequestBody.create(null, "en-US"))
            .addPart(/*  w w  w. j  a  v a 2s  . co m*/
                    Headers.of("Content-Disposition",
                            "form-data; name=\"image_request[image]\"; filename=\"testimage.jpg\""),
                    RequestBody.create(MEDIA_TYPE_JPG, new File(fileUri.getPath())))
            .build();

    Request request = new Request.Builder().header("Authorization", "CloudSight " + CLOUDSIGHT_KEY).url(reqUrl)
            .post(requestBody).build();

    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}

From source file:com.td.innovate.app.Activity.CaptureActivity.java

Call getKeywords(String token, Callback callback) throws Throwable {
    String tokenUrl = resUrl + token;

    Request request = new Request.Builder().header("Authorization", "CloudSight " + CLOUDSIGHT_KEY)
            .url(tokenUrl).build();//from ww  w .  ja va  2 s. c  om

    Call call = client.newCall(request);
    call.enqueue(callback);
    return call;
}

From source file:com.xing.api.CallSpec.java

License:Apache License

/**
 * Asynchronously send the request and notify {@code callback} of its response or if an error
 * occurred talking to the server, creating the request, or processing the response.
 * <p>/*from  w ww.j ava2  s.com*/
 * This method is <i>null-safe</i>, which means that there will be no failure or error propagated if
 * {@code callback} methods will throw an error.
 * <p>
 * Note that the {@code callback} will be dropped after the call execution.
 */
public void enqueue(final Callback<RT, ET> callback) {
    synchronized (this) {
        if (executed)
            throw stateError("Call already executed");
        executed = true;
    }

    Call rawCall;
    try {
        rawCall = createRawCall();
    } catch (Throwable t) {
        callback.onFailure(t);
        return;
    }
    if (canceled) {
        rawCall.cancel();
    }
    this.rawCall = rawCall;

    rawCall.enqueue(new com.squareup.okhttp.Callback() {
        private void callFailure(Throwable e) {
            try {
                callback.onFailure(e);
            } catch (Throwable t) {
                // TODO add some logging
            }
        }

        private void callSuccess(Response<RT, ET> response) {
            try {
                callback.onResponse(response);
            } catch (Throwable t) {
                // TODO add some logging
            }
        }

        @Override
        public void onFailure(Request request, IOException e) {
            callFailure(e);
        }

        @Override
        public void onResponse(com.squareup.okhttp.Response rawResponse) {
            Response<RT, ET> response;
            try {
                response = parseResponse(rawResponse);
            } catch (Throwable e) {
                callFailure(e);
                return;
            }
            callSuccess(response);
        }
    });
}