Search in sources :

Example 11 with DefaultRetryPolicy

use of com.android.volley.DefaultRetryPolicy in project Saiy-PS by brandall76.

the class BVEmotionAnalysis method getAnalysis.

/**
 * Method to get a temporary access token.
 *
 * @return an {@link Pair} of which the first parameter will denote success and the second an
 * {@link BVCredentials} object, containing the token credentials. If the request was unsuccessful,
 * the second parameter may be null.
 */
public Pair<Boolean, Emotions> getAnalysis(@NonNull final String recordingId, final int offset) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "getAnalysis");
    }
    final RequestFuture<String> future = RequestFuture.newFuture();
    final Cache cache = UtilsVolley.getCache(mContext);
    final Network network = new BasicNetwork(new HurlStack());
    final RequestQueue queue = new RequestQueue(cache, network);
    queue.start();
    final String url = ANALYSIS_URL + recordingId + FROM_MS + String.valueOf(offset);
    final StringRequest request = new StringRequest(Request.Method.GET, url, future, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(final VolleyError error) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "onErrorResponse: " + error.toString());
                BVEmotionAnalysis.this.verboseError(error);
            }
            queue.stop();
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            final Map<String, String> params = new HashMap<>();
            params.put(CHARSET, ENCODING);
            params.put(AUTHORIZATION, BEARER_ + token);
            return params;
        }
    };
    request.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(request);
    String response = null;
    try {
        response = future.get(THREAD_TIMEOUT, TimeUnit.SECONDS);
    } catch (final InterruptedException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "execute: InterruptedException");
            e.printStackTrace();
        }
    } catch (final ExecutionException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "execute: ExecutionException");
            e.printStackTrace();
        }
    } catch (final TimeoutException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "execute: TimeoutException");
            e.printStackTrace();
        }
    } finally {
        queue.stop();
    }
    if (response != null) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "onResponse: " + response);
            try {
                final JSONObject object = new JSONObject(response);
                MyLog.i(CLS_NAME, "object: " + object.toString(4));
            } catch (final JSONException e) {
                e.printStackTrace();
            }
        }
        final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        final Emotions emotions = gson.fromJson(response, Emotions.class);
        emotions.setRecordingId(recordingId);
        new AnalysisResultHelper(mContext, sl).interpretAndStore(emotions);
        return new Pair<>(true, emotions);
    } else {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "onResponse: failed");
        }
        return new Pair<>(false, null);
    }
}
Also used : HashMap(java.util.HashMap) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy) Gson(com.google.gson.Gson) RequestQueue(com.android.volley.RequestQueue) Network(com.android.volley.Network) BasicNetwork(com.android.volley.toolbox.BasicNetwork) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) Pair(android.util.Pair) VolleyError(com.android.volley.VolleyError) HurlStack(com.android.volley.toolbox.HurlStack) GsonBuilder(com.google.gson.GsonBuilder) StringRequest(com.android.volley.toolbox.StringRequest) JSONException(org.json.JSONException) AnalysisResultHelper(ai.saiy.android.cognitive.emotion.provider.beyondverbal.AnalysisResultHelper) Emotions(ai.saiy.android.cognitive.emotion.provider.beyondverbal.analysis.Emotions) Response(com.android.volley.Response) NetworkResponse(com.android.volley.NetworkResponse) BasicNetwork(com.android.volley.toolbox.BasicNetwork) JSONObject(com.nuance.dragon.toolkit.oem.api.json.JSONObject) Cache(com.android.volley.Cache)

Example 12 with DefaultRetryPolicy

use of com.android.volley.DefaultRetryPolicy in project ShoppingCart by joefei.

the class VollyHelperNew method sendRequestWithCallback.

/**
 * @param url    请求地址
 * @param method GET/POST
 * @param map    请求参数
 * @author ChenFurong
 */
public RequestQueue sendRequestWithCallback(String url, int method, Map<String, String> map, JSONObject jsonObject, final ResponseCallBack responseCallBack, final String infoSuccess, final String infoFailure, Object tag) {
    JSONObject jo = null;
    if (method != Method.GET && method != Method.DELETE && map != null) {
        jo = new JSONObject(map);
    }
    if (jsonObject != null) {
        jo = jsonObject;
    }
    JsonObjectRequest json = new JsonObjectRequest(method, url, jo, new Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            Log.e(VollyHelperNew.class.getName(), "onResponse=" + response.toString());
            String info = checkResponse(response, null, 0);
            int errCode = response.optInt(Constant.RESULT_KEY, -1);
            if (errCode == Constant.RESULT_SUCCESS) {
                /* 如果需要弹出且成功信息不为空 */
                if (isShowSuccess) {
                    if (infoSuccess != null) {
                        info = infoSuccess;
                    }
                    ToastHelper.getInstance()._toast(info);
                }
            } else {
                /* 如果需要弹出且失败信息不为空 */
                if (isShowError) {
                    if (infoFailure != null) {
                        info = infoFailure;
                    }
                    ToastHelper.getInstance()._toast(info);
                }
            }
            if (responseCallBack != null) {
                responseCallBack.handleResponse(response, errCode);
            }
            /* reset */
            isShowSuccess = false;
            isShowError = false;
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(VollyHelperNew.class.getName(), "onErrorResponse");
            if (responseCallBack != null) {
                Log.e(VollyHelperNew.class.getName(), "error=" + error.getMessage());
                responseCallBack.handleResponse(null, -1);
            }
        /* ToastHelper.getInstance()._toast("对不起,网络请求问题..."); */
        }
    }) {

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return TokenUtils.getHeaders(context);
        }

        @Override
        public void setRetryPolicy(RetryPolicy retryPolicy) {
            super.setRetryPolicy(retryPolicy);
        }
    };
    json.setRetryPolicy(new DefaultRetryPolicy(60000, 0, 1f) {

        @Override
        public int getCurrentRetryCount() {
            /*
				 * Volley默认尝试两次,MAX=1,count=0;count<=MAX;count++;count=2时,
				 * 表示当前已经重复请求两次,就不会再第三次重复请求,从而屏蔽掉Volley的自动重复请求功能;
				 */
            return 2;
        }
    });
    if (tag != null) {
        json.setTag(tag);
    } else {
        json.setTag(CANCLE_TAG);
    }
    mQueue.add(json);
    return mQueue;
}
Also used : Response(com.android.volley.Response) VolleyError(com.android.volley.VolleyError) JSONObject(org.json.JSONObject) ErrorListener(com.android.volley.Response.ErrorListener) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy) RetryPolicy(com.android.volley.RetryPolicy)

Example 13 with DefaultRetryPolicy

use of com.android.volley.DefaultRetryPolicy in project WordPress-Android by wordpress-mobile.

the class RestClientUtils method post.

/**
     * Make a JSON POST request
     */
public void post(final String path, JSONObject params, RetryPolicy retryPolicy, Listener listener, ErrorListener errorListener) {
    final JsonRestRequest request = mRestClient.makeRequest(mRestClient.getAbsoluteURL(path, getRestLocaleParams(mContext)), params, listener, errorListener);
    if (retryPolicy == null) {
        retryPolicy = new DefaultRetryPolicy(REST_TIMEOUT_MS, REST_MAX_RETRIES_POST, //Do not retry on failure
        REST_BACKOFF_MULT);
    }
    request.setRetryPolicy(retryPolicy);
    AuthenticatorRequest authCheck = new AuthenticatorRequest(request, errorListener, mRestClient, mAuthenticator);
    authCheck.send();
}
Also used : JsonRestRequest(com.wordpress.rest.JsonRestRequest) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy)

Example 14 with DefaultRetryPolicy

use of com.android.volley.DefaultRetryPolicy in project WordPress-Android by wordpress-mobile.

the class RestClientUtils method post.

/**
     * Make POST request with params
     */
public void post(final String path, Map<String, String> params, RetryPolicy retryPolicy, Listener listener, ErrorListener errorListener) {
    final RestRequest request = mRestClient.makeRequest(Method.POST, mRestClient.getAbsoluteURL(path, getRestLocaleParams(mContext)), params, listener, errorListener);
    if (retryPolicy == null) {
        retryPolicy = new DefaultRetryPolicy(REST_TIMEOUT_MS, REST_MAX_RETRIES_POST, //Do not retry on failure
        REST_BACKOFF_MULT);
    }
    request.setRetryPolicy(retryPolicy);
    AuthenticatorRequest authCheck = new AuthenticatorRequest(request, errorListener, mRestClient, mAuthenticator);
    authCheck.send();
}
Also used : RestRequest(com.wordpress.rest.RestRequest) JsonRestRequest(com.wordpress.rest.JsonRestRequest) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy)

Example 15 with DefaultRetryPolicy

use of com.android.volley.DefaultRetryPolicy in project Logdata-Android by AndroidLogData.

the class HttpService method requestLogData.

public void requestLogData(String apiKey, LogVO data, final HttpCallback callback) {
    String url = makeURL(TransferType.LOG_DATA);
    HttpOption option = httpOptionSetting(apiKey);
    JSONObject jsonObject = makeLogDataJSON(data);
    JsonCustomRequest request = new JsonCustomRequest(Request.Method.POST, url, option, jsonObject, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            try {
                Log.i("Response", response.get("result").toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VolleyError", "Log Transfer Error");
        }
    });
    request.setRetryPolicy(new DefaultRetryPolicy(2000, 5, 1));
    addRequestQueue(request);
}
Also used : Response(com.android.volley.Response) VolleyError(com.android.volley.VolleyError) JSONObject(org.json.JSONObject) JSONException(org.json.JSONException) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy)

Aggregations

DefaultRetryPolicy (com.android.volley.DefaultRetryPolicy)23 VolleyError (com.android.volley.VolleyError)15 Response (com.android.volley.Response)13 NetworkResponse (com.android.volley.NetworkResponse)10 RequestQueue (com.android.volley.RequestQueue)10 HashMap (java.util.HashMap)10 JSONObject (org.json.JSONObject)10 ExecutionException (java.util.concurrent.ExecutionException)9 TimeoutException (java.util.concurrent.TimeoutException)9 Pair (android.util.Pair)8 StringRequest (com.android.volley.toolbox.StringRequest)8 GsonBuilder (com.google.gson.GsonBuilder)8 JsonObjectRequest (com.android.volley.toolbox.JsonObjectRequest)7 Gson (com.google.gson.Gson)7 JsonRestRequest (com.wordpress.rest.JsonRestRequest)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)4 JSONException (org.json.JSONException)4 ErrorListener (com.android.volley.Response.ErrorListener)3 RestRequest (com.wordpress.rest.RestRequest)3 ProfileItem (ai.saiy.android.cognitive.identity.provider.microsoft.containers.ProfileItem)2