Example usage for com.squareup.okhttp OkHttpClient newCall

List of usage examples for com.squareup.okhttp OkHttpClient newCall

Introduction

In this page you can find the example usage for com.squareup.okhttp OkHttpClient newCall.

Prototype

public Call newCall(Request request) 

Source Link

Document

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

Usage

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// w ww .  ja va2 s .  com
        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  a2  s.  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.sam_chordas.android.stockhawk.service.HistoricData.HistoricData.java

License:Apache License

private String fetchData(String url) throws IOException {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(url).build();

    Response response = client.newCall(request).execute();

    return response.body().string();
}

From source file:com.sitexa.android.data.net.ApiConnection.java

License:Apache License

private void connectToApi() throws IOException {
    OkHttpClient okHttpClient = this.createClient();
    final Request request = new Request.Builder().url(this.url)
            .addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON).get().build();

    try {/*from w ww . j  av a  2 s  . c om*/
        this.response = okHttpClient.newCall(request).execute().body().string();
    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
        throw e;
    }
}

From source file:com.sitexa.android.data.net.okhttp.OkHttpApi.java

License:Apache License

private void doGet() {
    OkHttpClient okHttpClient = this.createClient();
    final Request request = new Request.Builder().url(this.url)
            .addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON).get().build();
    if (isThereInternetConnection()) {
        try {/*from w w w.  j  a v a  2 s.  co m*/
            String json = okHttpClient.newCall(request).execute().body().string();
            Log.d(TAG, json);
            Map map = gson.fromJson(json, Map.class);
            String code = (String) map.get(CodeConstants.HttpCode.CODE);
            Object value = map.get(CodeConstants.HttpCode.VALUE);

            if (CodeConstants.HttpCode.SUCCESS_CODE.equals(code)) {
                this.response = gson.toJson(value);
            } else {
                throw new RuntimeException(new NetworkConnectionException(
                        CodeConstants.ApiCode.ERROR + " : " + String.valueOf(code) + " : " + value.toString()));
            }
        } catch (Exception e) {
            throw new RuntimeException(new NetworkConnectionException(
                    CodeConstants.ApiCode.SERVER_CONNECTION_ERROR + " : " + e.getMessage()));
        }
    } else {
        throw new RuntimeException(new NetworkConnectionException());
    }
}

From source file:com.sitexa.android.data.net.okhttp.OkHttpApi.java

License:Apache License

private void doPost() {
    OkHttpClient okHttpClient = this.createClient();
    final Request request = new Request.Builder().url(this.url)
            .addHeader(CONTENT_TYPE_LABEL, CONTENT_TYPE_VALUE_JSON).post(requestBody).build();

    if (isThereInternetConnection()) {
        try {//from w ww  .  j av a  2  s.c o  m
            String json = okHttpClient.newCall(request).execute().body().string();
            Log.d(TAG, json);
            Map map = gson.fromJson(json, Map.class);
            String code = (String) map.get(CodeConstants.HttpCode.CODE);
            Object value = map.get(CodeConstants.HttpCode.VALUE);

            if (CodeConstants.HttpCode.SUCCESS_CODE.equals(code)) {
                this.response = gson.toJson(value);
            } else {
                throw new RuntimeException(new NetworkConnectionException(
                        CodeConstants.ApiCode.ERROR + ":" + String.valueOf(code) + ":" + value.toString()));
            }
        } catch (Exception e) {
            throw new RuntimeException(new NetworkConnectionException(
                    CodeConstants.ApiCode.SERVER_CONNECTION_ERROR + ":" + e.getMessage()));
        }
    } else {
        throw new RuntimeException(new NetworkConnectionException());
    }

}

From source file:com.sonaive.v2ex.sync.api.Api.java

License:Open Source License

public Bundle sync(HttpMethod httpMethod) {
    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = null;//w ww  .j ava 2 s.c om

    if (httpMethod == HttpMethod.GET) {
        request = new Request.Builder().url(mUrl).build();
    } else {
        String json = mArguments.getString(ARG_API_PARAMS);
        HashMap params = new Gson().fromJson(json, HashMap.class);
        FormEncodingBuilder formBodyBuilder = new FormEncodingBuilder();
        for (Map.Entry<String, String> entry : ((HashMap<String, String>) params).entrySet()) {
            formBodyBuilder.add(entry.getKey(), entry.getValue());
        }
        RequestBody formBody = formBodyBuilder.build();
        request = new Request.Builder().url(mUrl).post(formBody).build();
    }

    try {
        Response response = okHttpClient.newCall(request).execute();
        if (response != null && response.code() == 200) {
            LOGD(TAG, "Request: " + mUrl + ", server returned HTTP_OK, so fetching was successful.");
            mArguments.putString(Api.ARG_RESULT, response.body().string());
            return mArguments;
        } else if (response != null && response.code() == 403) {
            LOGW(TAG, "Request: " + mUrl + ", Server returned 403, fetching was failed.");
        } else {
            LOGW(TAG, "Request: " + mUrl + ", Fetching was failed. Unknown reason");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.sonaive.v2ex.sync.api.UserIdentityApi.java

License:Open Source License

public void verifyUserIdentity(final String accountName,
        final WeakReference<LoginHelper.Callbacks> callbacksRef) {

    OkHttpClient okHttpClient = new OkHttpClient();
    Request request = new Request.Builder().url(mUrl + "?username=" + accountName).build();

    okHttpClient.newCall(request).enqueue(new Callback() {

        @Override/*from ww  w.  j av  a 2s  . co m*/
        public void onFailure(Request request, IOException e) {
            JsonObject result = new JsonObject();
            result.addProperty("result", "fail");
            result.addProperty("err_msg", "IOException");
            if (callbacksRef != null) {
                callbacksRef.get().onIdentityCheckedFailed(result);
            }
        }

        @Override
        public void onResponse(Response response) throws IOException {
            JsonObject result = new JsonObject();
            if (response.code() == 200) {
                String responseBody = response.body().string();
                try {
                    JsonObject jsonObject = new Gson().fromJson(responseBody, JsonObject.class);
                    String status = jsonObject.get("status").getAsString();
                    if (status != null && status.equals("found")) {
                        result.addProperty("result", "ok");
                        LOGD(TAG, "userInfo: " + responseBody);
                        AccountUtils.setActiveAccount(mContext, accountName);
                        V2exDataHandler dataHandler = new V2exDataHandler(mContext);

                        Bundle data = new Bundle();
                        data.putString(Api.ARG_RESULT, responseBody);
                        data.putString(V2exDataHandler.ARG_DATA_KEY, V2exDataHandler.DATA_KEY_MEMBERS);
                        dataHandler.applyData(new Bundle[] { data });

                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedSuccess(result);
                        }
                    } else if (status != null && status.equals("notfound")) {
                        result.addProperty("result", "fail");
                        result.addProperty("err_msg", mContext.getString(R.string.err_user_not_found));
                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedFailed(result);
                        }
                    } else {
                        result.addProperty("result", "fail");
                        result.addProperty("err_msg", mContext.getString(R.string.err_unknown_error));
                        if (callbacksRef != null) {
                            callbacksRef.get().onIdentityCheckedFailed(result);
                        }
                    }
                } catch (JsonSyntaxException e) {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", "JsonSyntaxException");
                    if (callbacksRef != null) {
                        callbacksRef.get().onIdentityCheckedFailed(result);
                    }
                } catch (UnsupportedOperationException e) {
                    result.addProperty("result", "fail");
                    result.addProperty("err_msg", "UnsupportedOperationException");
                    if (callbacksRef != null) {
                        callbacksRef.get().onIdentityCheckedFailed(result);
                    }
                }
            } else if (response.code() == 403) {
                result.addProperty("result", "fail");
                result.addProperty("err_msg", "403 Forbidden");
                if (callbacksRef != null) {
                    callbacksRef.get().onIdentityCheckedFailed(result);
                }
            }
            LOGD(TAG, "responseCode: " + response.code() + ", result: " + result.get("result") + ", err_msg: "
                    + result.get("err_msg"));
        }
    });
}

From source file:com.spotify.apollo.http.client.HttpClient.java

License:Apache License

@Override
public CompletionStage<com.spotify.apollo.Response<ByteString>> send(com.spotify.apollo.Request apolloRequest,
        Optional<com.spotify.apollo.Request> apolloIncomingRequest) {

    final Optional<RequestBody> requestBody = apolloRequest.payload().map(payload -> {
        final MediaType contentType = apolloRequest.header("Content-Type").map(MediaType::parse)
                .orElse(DEFAULT_CONTENT_TYPE);
        return RequestBody.create(contentType, payload);
    });/*  w w w.jav  a  2 s  .  c o m*/

    Headers.Builder headersBuilder = new Headers.Builder();
    apolloRequest.headers().asMap().forEach((k, v) -> headersBuilder.add(k, v));

    apolloIncomingRequest.flatMap(req -> req.header(AUTHORIZATION_HEADER))
            .ifPresent(header -> headersBuilder.add(AUTHORIZATION_HEADER, header));

    final Request request = new Request.Builder().method(apolloRequest.method(), requestBody.orElse(null))
            .url(apolloRequest.uri()).headers(headersBuilder.build()).build();

    final CompletableFuture<com.spotify.apollo.Response<ByteString>> result = new CompletableFuture<>();

    //https://github.com/square/okhttp/wiki/Recipes#per-call-configuration
    OkHttpClient finalClient = client;
    if (apolloRequest.ttl().isPresent() && client.getReadTimeout() != apolloRequest.ttl().get().toMillis()) {
        finalClient = client.clone();
        finalClient.setReadTimeout(apolloRequest.ttl().get().toMillis(), TimeUnit.MILLISECONDS);
    }

    finalClient.newCall(request).enqueue(TransformingCallback.create(result));

    return result;
}

From source file:com.survivingwithandroid.ubiapp.UbidotsClient.java

License:Apache License

public void handleUbidots(String varId, String apiKey, final UbiListener listener) {

    final List<Value> results = new ArrayList<>();

    OkHttpClient client = new OkHttpClient();
    Request req = new Request.Builder().addHeader("X-Auth-Token", apiKey)
            .url("http://things.ubidots.com/api/v1.6/variables/" + varId + "/values").build();

    client.newCall(req).enqueue(new Callback() {
        @Override//from ww w  . java 2 s.co  m
        public void onFailure(Request request, IOException e) {
            Log.d("Chart", "Network error");
            e.printStackTrace();
        }

        @Override
        public void onResponse(Response response) throws IOException {
            String body = response.body().string();
            Log.d("Chart", body);

            try {
                JSONObject jObj = new JSONObject(body);
                JSONArray jRes = jObj.getJSONArray("results");
                for (int i = 0; i < jRes.length(); i++) {
                    JSONObject obj = jRes.getJSONObject(i);
                    Value val = new Value();
                    val.timestamp = obj.getLong("timestamp");
                    val.value = (float) obj.getDouble("value");
                    results.add(val);
                }

                listener.onDataReady(results);

            } catch (JSONException jse) {
                jse.printStackTrace();
            }

        }
    });

}