Java Code Examples for com.android.volley.toolbox.StringRequest#setRetryPolicy()

The following examples show how to use com.android.volley.toolbox.StringRequest#setRetryPolicy() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: FindImageUrlLoader.java    From myapplication with Apache License 2.0 5 votes vote down vote up
/**
 * 获得第page页图片url * @param page 页数
 */
public void loadImageUrl(int page) {

    String dataUrl = String.format(DATA_URL, dataType, count, page);
    StringRequest request = new StringRequest(dataUrl, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            try {
                JSONObject obj = new JSONObject(response);
                JSONArray array = obj.getJSONArray("results");
                imageUrlList.clear();
                for (int i = 0; i < array.length(); i++) {
                    String url = array.getJSONObject(i).getString("url");//获得图片url
                    imageUrlList.add(url);
                }
                callback.addData(imageUrlList);

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            //加载出错
            Log.e(TAG, "error:" + error.getMessage());
            Toast.makeText(context, "加载出错", Toast.LENGTH_SHORT).show();
        }
    });
    request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT, 1, 1.0f));//设置请求超时
    BasicApplication.getInstance().addRequest(request);//将消息添加到消息队列
}
 
Example 2
Source File: GosScheduleSiteTool.java    From Gizwits-SmartBuld_Android with MIT License 5 votes vote down vote up
public void deleteTimeOnSite(String id, final OnResponListener reponse) {
	String httpurl = "http://api.gizwits.com/app/scheduler/" + id;
	StringRequest stringRequest = new StringRequest(Method.DELETE, httpurl, new Response.Listener<String>() {
		@Override
		public void onResponse(String arg0) {
			reponse.OnRespon(0, "OK");
		}
	}, new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			if (error.networkResponse != null) {
				if (error.networkResponse.statusCode == 404) {// 404:云端无法找到该条目,表示该条目已被删除
					reponse.OnRespon(0, "OK");
				}
			}
			reponse.OnRespon(1, error.toString());
			error.printStackTrace();
			Log.i("onSite", "删除失败" + error.toString());

		}
	}) {

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

	};
	stringRequest.setRetryPolicy(new DefaultRetryPolicy(2500, 3, 0));
	mRequestQueue.add(stringRequest);

}
 
Example 3
Source File: ApiRequest.java    From syncthing-android with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Opens the connection, then returns success status and response string.
 */
void connect(int requestMethod, Uri uri, @Nullable String requestBody,
             @Nullable OnSuccessListener listener, @Nullable OnErrorListener errorListener) {
    Log.v(TAG, "Performing request to " + uri.toString());
    StringRequest request = new StringRequest(requestMethod, uri.toString(), reply -> {
        if (listener != null) {
            listener.onSuccess(reply);
        }
    }, error -> {
        if (errorListener != null) {
            errorListener.onError(error);
        } else {
            Log.w(TAG, "Request to " + uri + " failed, " + error.getMessage());
        }
    }) {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            return ImmutableMap.of(HEADER_API_KEY, mApiKey);
        }

        @Override
        public byte[] getBody() throws AuthFailureError {
            return Optional.fromNullable(requestBody).transform(String::getBytes).orNull();
        }
    };

    // Some requests seem to be slow or fail, make sure this doesn't break the app
    // (eg if an event request fails, new event requests won't be triggered).
    request.setRetryPolicy(new DefaultRetryPolicy(5000, 5,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    getVolleyQueue().add(request);
}
 
Example 4
Source File: LyricsChart.java    From QuickLyric with GNU General Public License v3.0 5 votes vote down vote up
public static com.android.volley.Request getVolleyRequest(boolean lrc, Listener<String> listener,
                                                          ErrorListener errorListener, Chromaprint.Fingerprint fingerprint, String... args) throws Exception {
    String url = String.format("http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect?artist=%s&song=%s", URLEncoder.encode(args[0], "UTF-8"), URLEncoder.encode(args[1], "UTF-8"));
    StringRequest request = new StringRequest(com.android.volley.Request.Method.GET, url, listener, errorListener);
    request.setRetryPolicy(new DefaultRetryPolicy(10000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    return request;
}
 
Example 5
Source File: ManageFeedsActivity.java    From indigenous-android with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get feeds in channel.
 */
public void getFeeds() {

    if (!Utility.hasConnection(getApplicationContext())) {
        showRefreshMessage = false;
        checkRefreshingStatus();
        Snackbar.make(layout, getString(R.string.no_connection), Snackbar.LENGTH_SHORT).show();
        noConnection.setVisibility(View.VISIBLE);
        return;
    }

    String MicrosubEndpoint = user.getMicrosubEndpoint();
    MicrosubEndpoint += "?action=follow&channel=" + channelId;

    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

    StringRequest getRequest = new StringRequest(Request.Method.GET, MicrosubEndpoint,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {

                    try {
                        JSONObject object;
                        JSONObject microsubResponse = new JSONObject(response);
                        JSONArray itemList = microsubResponse.getJSONArray("items");

                        for (int i = 0; i < itemList.length(); i++) {
                            object = itemList.getJSONObject(i);
                            Feed item = new Feed();
                            item.setUrl(object.getString("url"));
                            item.setChannel(channelId);
                            FeedItems.add(item);
                        }

                        adapter.notifyDataSetChanged();
                    }
                    catch (JSONException e) {
                        showRefreshMessage = false;
                        String message = String.format(getString(R.string.feed_parse_error), e.getMessage());
                        final Snackbar snack = Snackbar.make(layout, message, Snackbar.LENGTH_INDEFINITE);
                        snack.setAction(getString(R.string.close), new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    snack.dismiss();
                                }
                            }
                        );
                        snack.show();

                    }

                    checkRefreshingStatus();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    showRefreshMessage = false;
                    Snackbar.make(layout, getString(R.string.no_feeds_found), Snackbar.LENGTH_SHORT).show();
                    checkRefreshingStatus();
                }
            }
    )
    {
        @Override
        public Map<String, String> getHeaders() {
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Accept", "application/json");
            headers.put("Authorization", "Bearer " + user.getAccessToken());
            return headers;
        }

    };

    getRequest.setRetryPolicy(new DefaultRetryPolicy(
            0,
            -1,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    queue.add(getRequest);

}
 
Example 6
Source File: DeleteIDProfile.java    From Saiy-PS with GNU Affero General Public License v3.0 4 votes vote down vote up
public void delete() {

        final long then = System.nanoTime();

        String url = null;

        try {
            url = DELETE_URL + URLEncoder.encode(profileId, Constants.ENCODING_UTF8);
        } catch (final UnsupportedEncodingException e) {
            if (DEBUG) {
                MyLog.w(CLS_NAME, "delete: UnsupportedEncodingException");
                e.printStackTrace();
            }
        }

        final RequestQueue queue = Volley.newRequestQueue(mContext);
        queue.start();

        final StringRequest stringRequest = new StringRequest(Request.Method.DELETE, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(final String response) {
                        if (DEBUG) {
                            MyLog.i(CLS_NAME, "onResponse: success");
                        }
                        queue.stop();
                    }
                },

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

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                final Map<String, String> params = new HashMap<>();
                params.put(CHARSET, Constants.ENCODING_UTF8);
                params.put(OCP_SUBSCRIPTION_KEY_HEADER, apiKey);
                return params;
            }
        };

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);

        if (DEBUG) {
            MyLog.getElapsed(CLS_NAME, then);
        }

    }
 
Example 7
Source File: GosScheduleSiteTool.java    From Gizwits-SmartBuld_Android with MIT License 4 votes vote down vote up
/**
 * <p>
 * Description:
 * </p>
 */
public void getTimeOnSite(final OnResponseGetDeviceDate response) {

	String httpurl = "http://api.gizwits.com/app/scheduler";
	StringRequest stringRequest = new StringRequest(Method.GET, httpurl, new Response.Listener<String>() {
		@Override
		public void onResponse(String arg0) {
			Log.i("onSite", "-------------");
			Log.i("onSite", arg0);
			dataList = new ArrayList<ConcurrentHashMap<String, Object>>();
			try {
				JSONArray js = new JSONArray(arg0);
				for (int i = 0; i < js.length(); i++) {
					JSONObject jo = js.getJSONObject(i);
					ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<String, Object>();
					map.put("date", jo.optString("date"));
					map.put("time", jo.optString("time"));
					map.put("repeat", jo.optString("repeat"));
					map.put("did", getDidFromJsonObject(jo));
					map.put("dataMap", getDateFromJsonObject(jo));
					map.put("ruleID", jo.optString("id"));
					dataList.add(map);
				}
				response.onReceviceDate(dataList);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}, new Response.ErrorListener() {
		@Override
		public void onErrorResponse(VolleyError error) {
			response.onReceviceDate(null);
			error.printStackTrace();
			Log.i("onSite", "获取设备状态请求失败" + error.toString() + error.getNetworkTimeMs());
		}
	}) {

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

	};
	stringRequest.setRetryPolicy(new DefaultRetryPolicy(2500, 4, 0));
	mRequestQueue.add(stringRequest);
}