Search in sources :

Example 11 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest in project MPW by shineangelic.

the class NoobPoolInstrumentedTest method testJsonRequest.

@Test
public void testJsonRequest() throws Exception {
    final GsonBuilder builder = new GsonBuilder();
    // gestione UNIX time lungo e non
    builder.registerTypeAdapter(Date.class, new MyDateTypeAdapter());
    builder.registerTypeAdapter(Calendar.class, new MyTimeStampTypeAdapter());
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, Utils.getHomeStatsURL(sharedPreferences), null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(final JSONObject response) {
            Log.d(Constants.TAG, response.toString());
            Gson gson = builder.create();
            // Register an adapter to manage the date types as long values
            HomeStats retrieved = gson.fromJson(response.toString(), HomeStats.class);
            assertNotNull(retrieved);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(Constants.TAG, "Error: " + error.getMessage());
            fail();
        // hide the progress dialog
        }
    });
    // Adding request to request queue
    JSONClientSingleton.getInstance(InstrumentationRegistry.getTargetContext()).addToRequestQueue(jsonObjReq);
}
Also used : Response(com.android.volley.Response) VolleyError(com.android.volley.VolleyError) JSONObject(org.json.JSONObject) GsonBuilder(com.google.gson.GsonBuilder) MyDateTypeAdapter(it.angelic.mpw.model.MyDateTypeAdapter) MyTimeStampTypeAdapter(it.angelic.mpw.model.MyTimeStampTypeAdapter) Gson(com.google.gson.Gson) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) Test(org.junit.Test)

Example 12 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest in project MPW by shineangelic.

the class NoobPoolInstrumentedTest method testJsonWalletRequest.

@Test
public void testJsonWalletRequest() throws Exception {
    final GsonBuilder builder = new GsonBuilder();
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, Utils.getWalletStatsUrl(sharedPreferences) + minerAddr, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(final JSONObject response) {
            Log.i(Constants.TAG, response.toString());
            Gson gson = builder.create();
            // Register an adapter to manage the date types as long values
            Wallet retrieved = gson.fromJson(response.toString(), Wallet.class);
            assertNotNull(retrieved);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(Constants.TAG, "Error: " + error.getMessage());
        }
    });
    // Adding request to request queue
    JSONClientSingleton.getInstance(appContext).addToRequestQueue(jsonObjReq);
}
Also used : Response(com.android.volley.Response) VolleyError(com.android.volley.VolleyError) JSONObject(org.json.JSONObject) GsonBuilder(com.google.gson.GsonBuilder) Wallet(it.angelic.mpw.model.jsonpojos.wallet.Wallet) Gson(com.google.gson.Gson) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) Test(org.junit.Test)

Example 13 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest in project MPW by shineangelic.

the class MaxHashInstrumentedTest method testJsonRequest.

@Test
public void testJsonRequest() throws Exception {
    final GsonBuilder builder = new GsonBuilder();
    // gestione UNIX time lungo e non
    builder.registerTypeAdapter(Date.class, new MyDateTypeAdapter());
    builder.registerTypeAdapter(Calendar.class, new MyTimeStampTypeAdapter());
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, Utils.getHomeStatsURL(sharedPreferences), null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(final JSONObject response) {
            Log.d(Constants.TAG, response.toString());
            Gson gson = builder.create();
            // Register an adapter to manage the date types as long values
            HomeStats retrieved = gson.fromJson(response.toString(), HomeStats.class);
            assertNotNull(retrieved);
        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(Constants.TAG, "Error: " + error.getMessage());
            fail();
        // hide the progress dialog
        }
    });
    // Adding request to request queue
    JSONClientSingleton.getInstance(InstrumentationRegistry.getTargetContext()).addToRequestQueue(jsonObjReq);
}
Also used : Response(com.android.volley.Response) VolleyError(com.android.volley.VolleyError) JSONObject(org.json.JSONObject) GsonBuilder(com.google.gson.GsonBuilder) MyDateTypeAdapter(it.angelic.mpw.model.MyDateTypeAdapter) MyTimeStampTypeAdapter(it.angelic.mpw.model.MyTimeStampTypeAdapter) Gson(com.google.gson.Gson) HomeStats(it.angelic.mpw.model.jsonpojos.home.HomeStats) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) Test(org.junit.Test)

Example 14 with JsonObjectRequest

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

the class FetchIDProfile method getProfile.

/**
 * Method to get an enrollment id.
 *
 * @return an {@link Pair} of which the first parameter will denote success and the second an
 * {@link ProfileItem} object. If the request was unsuccessful,
 * the second parameter may be null.
 */
public Pair<Boolean, ProfileItem> getProfile() {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "getProfile");
    }
    final long then = System.nanoTime();
    String url = null;
    try {
        url = FETCH_URL + URLEncoder.encode(profileId, ENCODING);
    } catch (final UnsupportedEncodingException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "getProfile: UnsupportedEncodingException");
            e.printStackTrace();
        }
    }
    final RequestFuture<JSONObject> future = RequestFuture.newFuture();
    final RequestQueue queue = Volley.newRequestQueue(mContext);
    queue.start();
    final JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET, url, null, future, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(final VolleyError error) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "onErrorResponse: " + error.toString());
                FetchIDProfile.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(JSON_HEADER_ACCEPT, JSON_HEADER_VALUE_ACCEPT);
            params.put(OCP_SUBSCRIPTION_KEY_HEADER, apiKey);
            return params;
        }
    };
    jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(jsonObjReq);
    JSONObject response = null;
    try {
        response = future.get(THREAD_TIMEOUT, TimeUnit.SECONDS);
    } catch (final InterruptedException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "getProfile: InterruptedException");
            e.printStackTrace();
        }
    } catch (final ExecutionException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "getProfile: ExecutionException");
            e.printStackTrace();
        }
    } catch (final TimeoutException e) {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "getProfile: TimeoutException");
            e.printStackTrace();
        }
    } finally {
        queue.stop();
    }
    if (DEBUG) {
        MyLog.getElapsed(CLS_NAME, then);
    }
    if (response != null) {
        if (DEBUG) {
            MyLog.i(CLS_NAME, "response: " + response.toString());
        }
        final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        final ProfileItem profileItem = gson.fromJson(response.toString(), ProfileItem.class);
        if (DEBUG) {
            MyLog.i(CLS_NAME, "response: getId: " + profileItem.getId());
        }
        return new Pair<>(true, profileItem);
    } else {
        if (DEBUG) {
            MyLog.w(CLS_NAME, "response: failed");
        }
        return new Pair<>(false, null);
    }
}
Also used : VolleyError(com.android.volley.VolleyError) ProfileItem(ai.saiy.android.cognitive.identity.provider.microsoft.containers.ProfileItem) HashMap(java.util.HashMap) GsonBuilder(com.google.gson.GsonBuilder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DefaultRetryPolicy(com.android.volley.DefaultRetryPolicy) Gson(com.google.gson.Gson) Response(com.android.volley.Response) NetworkResponse(com.android.volley.NetworkResponse) JSONObject(org.json.JSONObject) RequestQueue(com.android.volley.RequestQueue) JsonObjectRequest(com.android.volley.toolbox.JsonObjectRequest) ExecutionException(java.util.concurrent.ExecutionException) TimeoutException(java.util.concurrent.TimeoutException) Pair(android.util.Pair)

Example 15 with JsonObjectRequest

use of com.android.volley.toolbox.JsonObjectRequest 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)

Aggregations

JsonObjectRequest (com.android.volley.toolbox.JsonObjectRequest)109 JSONObject (org.json.JSONObject)109 VolleyError (com.android.volley.VolleyError)97 Response (com.android.volley.Response)95 HashMap (java.util.HashMap)62 RequestQueue (com.android.volley.RequestQueue)59 User (model.User)50 JSONException (org.json.JSONException)45 Gson (com.google.gson.Gson)24 Context (android.content.Context)18 Test (org.junit.Test)18 Toast (android.widget.Toast)17 GsonBuilder (com.google.gson.GsonBuilder)17 NetworkResponse (com.android.volley.NetworkResponse)12 TextView (android.widget.TextView)9 DefaultRetryPolicy (com.android.volley.DefaultRetryPolicy)7 Wallet (it.angelic.mpw.model.jsonpojos.wallet.Wallet)7 HomeStats (it.angelic.mpw.model.jsonpojos.home.HomeStats)5 Intent (android.content.Intent)4 Pair (android.util.Pair)4