Java Code Examples for com.android.volley.DefaultRetryPolicy

The following examples show how to use com.android.volley.DefaultRetryPolicy. These examples are extracted from open source projects. 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 Project: base-module   Source File: VolleyRequest.java    License: Apache License 2.0 6 votes vote down vote up
public <T> void createRequest(VolleyListener<T> listener) {
    VolleyResponse<T> volleyResponse = new VolleyResponse<T>(listener, this);
    StringRequestWrapper request = new StringRequestWrapper(mMethod, mUrl, volleyResponse, volleyResponse);
    mRequest = request;
    if (VolleyManager.sGlobalTimeout > 0) {
        mTimeOutMs = VolleyManager.sGlobalTimeout * 1000;
    }
    if (VolleyManager.sGlobalMaxRetryCount > 0) {
        mMaxNumRetries = VolleyManager.sGlobalMaxRetryCount;
    }
    if (mTimeOutMs != DefaultRetryPolicy.DEFAULT_TIMEOUT_MS || mMaxNumRetries != DefaultRetryPolicy.DEFAULT_MAX_RETRIES) {
        request.setRetryPolicy(new DefaultRetryPolicy(mTimeOutMs, mMaxNumRetries, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
    mParamsMap.putAll(VolleyManager.sGlobalParamsMap);
    mHeadersMap.putAll(VolleyManager.sGlobalHeadersMap);
    request.setHeadersMap(mHeadersMap);
    request.setParamsMap(mParamsMap);
    request.setTag(mTag);

    VolleyQueueSingleton.getInstance().add(request);
}
 
Example 2
Source Project: volley   Source File: ImageRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new image request, decoding to a maximum specified width and height. If both width
 * and height are zero, the image will be decoded to its natural size. If one of the two is
 * nonzero, that dimension will be clamped and the other one will be set to preserve the image's
 * aspect ratio. If both width and height are nonzero, the image will be decoded to be fit in
 * the rectangle of dimensions width x height while keeping its aspect ratio.
 *
 * @param url URL of the image
 * @param listener Listener to receive the decoded bitmap
 * @param maxWidth Maximum width to decode this bitmap to, or zero for none
 * @param maxHeight Maximum height to decode this bitmap to, or zero for none
 * @param scaleType The ImageViews ScaleType used to calculate the needed image size.
 * @param decodeConfig Format to decode the bitmap to
 * @param errorListener Error listener, or null to ignore errors
 */
public ImageRequest(
        String url,
        Response.Listener<Bitmap> listener,
        int maxWidth,
        int maxHeight,
        ScaleType scaleType,
        Config decodeConfig,
        @Nullable Response.ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    setRetryPolicy(
            new DefaultRetryPolicy(
                    DEFAULT_IMAGE_TIMEOUT_MS,
                    DEFAULT_IMAGE_MAX_RETRIES,
                    DEFAULT_IMAGE_BACKOFF_MULT));
    mListener = listener;
    mDecodeConfig = decodeConfig;
    mMaxWidth = maxWidth;
    mMaxHeight = maxHeight;
    mScaleType = scaleType;
}
 
Example 3
Source Project: JianDan_OkHttpWithVolley   Source File: RequestManager.java    License: Apache License 2.0 6 votes vote down vote up
public static void addRequest(Request<?> request, Object tag) {
    if (tag != null) {
        request.setTag(tag);
    }
    //给每个请求重设超时、重试次数
    request.setRetryPolicy(new DefaultRetryPolicy(
            OUT_TIME,
            TIMES_OF_RETRY,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    mRequestQueue.add(request);

    if (BuildConfig.DEBUG) {
        Logger.d(request.getUrl());
    }

}
 
Example 4
Source Project: JianDan   Source File: RequestManager.java    License: Apache License 2.0 6 votes vote down vote up
public static void addRequest(Request<?> request, Object tag) {
    if (tag != null) {
        request.setTag(tag);
    }
    //给每个请求重设超时、重试次数
    request.setRetryPolicy(new DefaultRetryPolicy(
            OUT_TIME,
            TIMES_OF_RETRY,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    mRequestQueue.add(request);

    if (BuildConfig.DEBUG) {
        Logger.d(request.getUrl());
    }

}
 
Example 5
Source Project: seny-devpkg   Source File: HttpLoader.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 初始化一个GsonRequest
 *
 * @param method      请求方法
 * @param url         请求地址
 * @param params      请求参数,可以为null
 * @param clazz       Clazz类型,用于GSON解析json字符串封装数据
 * @param requestCode 请求码 每次请求对应一个code作为改Request的唯一标识
 * @param listener    监听器用来响应结果
 * @return 返回一个GsonRequest对象
 */
private GsonRequest<IResponse> makeGsonRequest(int method, String url, final HttpParams params, Class<? extends IResponse> clazz, int requestCode, HttpListener listener, boolean isCache) {
    ResponseListener responseListener = new ResponseListener(requestCode, listener);
    Map<String, String> paramsMap = null;//默认为null
    Map<String, String> headerMap = null;//默认为null
    if (params != null) {//如果有参数,则构建参数
        if (method == Request.Method.GET) {
            url = url + params.toGetParams();//如果是get请求,则把参数拼在url后面
        } else {
            paramsMap = params.getParams();//如果不是get请求,取出HttpParams中的Map参数集合。
        }
        headerMap = params.getHeaders();//获取设置的header信息
    }
    GsonRequest<IResponse> request = new GsonRequest<>(method, url, paramsMap, headerMap, clazz, responseListener, responseListener, isCache, mContext);
    request.setRetryPolicy(new DefaultRetryPolicy());//设置超时时间,重试次数,重试因子(1,1*2,2*2,4*2)等
    return request;
}
 
Example 6
Source Project: EasyVolley   Source File: ASFRequest.java    License: Apache License 2.0 6 votes vote down vote up
public void start() {
    if (mRequestQueueWeakReference.get() != null && getRequest() != null) {
        if (shouldUseCache() && isCachableHTTPMethod() && getCache() != null) {
            ASFCache.ASFEntry entry = getCache().get(getCacheKey());
            if (entry != null) {
                try {
                    getResponseListener().onResponse((T) entry.getData());
                    return;
                }catch (ClassCastException e) {}
            }
        }

        if (!shouldUseCache()) {
            getRequest().setShouldCache(false);
        }
        getRequest().setRetryPolicy(new DefaultRetryPolicy(
                mNetworkTimeoutTime,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mRequestQueueWeakReference.get().add(getRequest());
        mRequestQueueWeakReference.get().start();
        EasyVolley.addedRequest(this);
    }
}
 
Example 7
Source Project: JianDan_OkHttp   Source File: RequestManager.java    License: Apache License 2.0 6 votes vote down vote up
public static void addRequest(Request<?> request, Object tag) {
    if (tag != null) {
        request.setTag(tag);
    }
    //给每个请求重设超时、重试次数
    request.setRetryPolicy(new DefaultRetryPolicy(
            OUT_TIME,
            TIMES_OF_RETRY,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

    mRequestQueue.add(request);

    if (BuildConfig.DEBUG) {
        Logger.d(request.getUrl());
    }

}
 
Example 8
Source Project: volley   Source File: ImageRequest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new image request, decoding to a maximum specified width and
 * height. If both width and height are zero, the image will be decoded to
 * its natural size. If one of the two is nonzero, that dimension will be
 * clamped and the other one will be set to preserve the image's aspect
 * ratio. If both width and height are nonzero, the image will be decoded to
 * be fit in the rectangle of dimensions width x height while keeping its
 * aspect ratio.
 *
 * @param url URL of the image
 * @param listener Listener to receive the decoded bitmap
 * @param maxWidth Maximum width to decode this bitmap to, or zero for none
 * @param maxHeight Maximum height to decode this bitmap to, or zero for
 *            none
 * @param decodeConfig Format to decode the bitmap to
 * @param errorListener Error listener, or null to ignore errors
 */
public ImageRequest(Context context,String url, Response.Listener<Bitmap> listener, int maxWidth, int maxHeight,
        Config decodeConfig, Response.ErrorListener errorListener) {
    super(Method.GET, url, errorListener);
    setRetryPolicy(
            new DefaultRetryPolicy(IMAGE_TIMEOUT_MS, IMAGE_MAX_RETRIES, IMAGE_BACKOFF_MULT));
    mListener = listener;
    mDecodeConfig = decodeConfig;
    mMaxWidth = maxWidth;
    mMaxHeight = maxHeight;
    mContext = context;
    // 如果加载的是本地图片,不放入disk-cache目录
    if (url.startsWith("http") || url.startsWith("https")) {
        setShouldCache(true);
    } else {
        setShouldCache(false);
    }
    setShouldGzip(false);
}
 
Example 9
Source Project: CrossBow   Source File: WearDataRequest.java    License: Apache License 2.0 6 votes vote down vote up
public WearDataRequest(int method, String url, String uuid, String transformerKey, int retryCount, int timeout,
                       String cacheKey, String tag, String bodyContentType, Map<String, String> headers,
                       byte[] body, Priority priority, ParamsBundle transformerArgs) {
    super(method, url, null);
    this.uuid = uuid;
    this.cacheKey = cacheKey;
    this.tag = tag;
    this.bodyContentType = bodyContentType;
    this.headers = headers;
    this.body = body;
    this.priority = priority;
    this.transformerArgs = transformerArgs;
    this.transformerMap.putAll(transformerMap);
    this.retryPolicy = new DefaultRetryPolicy(timeout, retryCount, 1f);
    this.transformerKey = transformerKey;
    setRetryPolicy(retryPolicy);
}
 
Example 10
Source Project: volley-jackson-extension   Source File: JacksonRequest.java    License: Apache License 2.0 6 votes vote down vote up
public JacksonRequest(int timeout, int method, String url, Map<String, String> params, JacksonRequestListener<T> listener) {
	super(method, url, null);

	setShouldCache(false);

	mListener = listener;

	mAcceptedStatusCodes = new ArrayList<Integer>();
	mAcceptedStatusCodes.add(HttpStatus.SC_OK);
	mAcceptedStatusCodes.add(HttpStatus.SC_NO_CONTENT);

	setRetryPolicy(new DefaultRetryPolicy(timeout, 1, 1));

	if (method == Method.POST || method == Method.PUT) {
		mParams = params;
	}
}
 
Example 11
Source Project: TDTChannels-APP   Source File: VolleyController.java    License: MIT License 5 votes vote down vote up
public void addToQueue(Request request) {
    if (request != null) {
        request.setTag(this);
        if (fRequestQueue == null)
            fRequestQueue = volley.getRequestQueue();
        request.setRetryPolicy(new DefaultRetryPolicy(
                60000, 3, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT
        ));
        fRequestQueue.add(request);
    }
}
 
Example 12
Source Project: CoolClock   Source File: NetworkService.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void setRequestTimeout(int ms) {
    int timeout = (ms == 0) ? DefaultRetryPolicy.DEFAULT_TIMEOUT_MS : ms;

    mRetryPolicy = new DefaultRetryPolicy(timeout,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
}
 
Example 13
Source Project: myapplication   Source File: FindImageUrlLoader.java    License: 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 14
/**
 * Add request to queue using specific tag
 *
 * @param request
 * @param tag
 */
public <T> void addToRequestQueue(Request<T> request, String tag) {
    // set retry policy
    Log.d("debug", request.getUrl());
    request.setRetryPolicy(new DefaultRetryPolicy(
            TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    getRequestQueue().add(request);
}
 
Example 15
Source Project: AndNet   Source File: VolleyManager.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 添加一个请求
 * @param request
 */
public <T> void add(Request<T> request) {
	// 重试策略
	request.setRetryPolicy(new DefaultRetryPolicy(5000,
			DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
			DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
	mRequestQueue.add(request);
}
 
Example 16
Source Project: Gizwits-SmartBuld_Android   Source File: GosScheduleSiteTool.java    License: 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 17
Source Project: volley   Source File: DownloadRequest.java    License: Apache License 2.0 5 votes vote down vote up
public DownloadRequest(String url, Listener<String> listener, ErrorListener errorListener,
        LoadingListener loadingListener) {
    super(Method.GET, url, listener, errorListener, loadingListener);
    // 下载文件大,失败可能性比较大,所以加大retry次数
    setRetryPolicy(
            new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS, 5, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    // 关闭gzip
    setShouldGzip(false);
}
 
Example 18
Source Project: volley   Source File: MultiPartRequest.java    License: Apache License 2.0 5 votes vote down vote up
public MultiPartRequest(int method, String url, Listener<T> listener, ErrorListener errorlistener, LoadingListener loadingListener) {

        super(method, url, errorlistener);
        mListener = listener;
        
        mMultipartEntity = new UploadMultipartEntity();
        
        final ExecutorDelivery delivery = new ExecutorDelivery(new Handler(Looper.getMainLooper()));
        setLoadingListener(loadingListener);
        if (loadingListener != null) {
            mMultipartEntity.setListener(new ProgressListener() {
                long time = SystemClock.uptimeMillis();
                long count = -1;
                
                @Override
                public void transferred(long num) {
                    if (count == -1) {
                        count = mMultipartEntity.getContentLength();
                    }
                    // LogUtils.d("bacy", "upload->" + count + ",num->" + num);
                    long thisTime = SystemClock.uptimeMillis();
                    if (thisTime - time >= getRate() || count == num) {
                        time = thisTime;
                        delivery.postLoading(MultiPartRequest.this, count, num);
                    }
                }
            });
        }
        setRetryPolicy(new DefaultRetryPolicy(TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }
 
Example 19
Source Project: example   Source File: BaseApplication.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Add request to queue using specific tag
 *
 * @param request
 * @param tag
 */
public <T> void addToRequestQueue(Request<T> request, String tag) {
    // set retry policy
    Log.d("debug", request.getUrl());
    request.setRetryPolicy(new DefaultRetryPolicy(
            TIMEOUT_MS,
            DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
            DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    getRequestQueue().add(request);
}
 
Example 20
Source Project: syncthing-android   Source File: ApiRequest.java    License: 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 21
Source Project: barterli_android   Source File: MultiPartRequest.java    License: Apache License 2.0 5 votes vote down vote up
public MultiPartRequest(int method, String url, Listener<T> listener, ErrorListener errorlistener) {

        super(method, url, errorlistener, new DefaultRetryPolicy(TIMEOUT_MS, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        mListener = listener;
        mMultipartParams = new HashMap<String, MultiPartRequest.MultiPartParam>();
        mFileUploads = new HashMap<String, String>();
        
    }
 
Example 22
Source Project: QuickLyric   Source File: LyricsChart.java    License: 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 23
Source Project: CrossBow   Source File: WearDataRequestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    transformerArgs.putString("arg1", UUID.randomUUID().toString());
    transformerArgs.putString("arg2", UUID.randomUUID().toString());

    headers.put("arg1", UUID.randomUUID().toString());
    headers.put("arg2", UUID.randomUUID().toString());
    retryPolicy = new DefaultRetryPolicy(3685, 7, 0.4f);
}
 
Example 24
Source Project: renrenpay-android   Source File: StringRequestGet.java    License: Apache License 2.0 4 votes vote down vote up
public StringRequestGet(String url, Response.Listener<String> listener, @Nullable Response.ErrorListener errorListener) {
    super(Method.GET, url, null, listener, errorListener);
    setRetryPolicy(new DefaultRetryPolicy(5000, 0, 0));
}
 
Example 25
/**
 * 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 26
Source Project: Tpay   Source File: StringRequestGet.java    License: GNU General Public License v3.0 4 votes vote down vote up
public StringRequestGet(String url, Response.Listener<String> listener, @Nullable Response.ErrorListener errorListener) {
    super(Method.GET, url, null, listener, errorListener);
    setRetryPolicy(new DefaultRetryPolicy(5000, 0, 0));
}
 
Example 27
Source Project: Tpay   Source File: FastJsonRequest.java    License: GNU General Public License v3.0 4 votes vote down vote up
public FastJsonRequest(String url, Response.Listener<BaseMsg> listener, @Nullable Response.ErrorListener errorListener) {
    super(Method.GET, url, null, listener, errorListener);
    setRetryPolicy(new DefaultRetryPolicy(5000, 0, 0));
}
 
Example 28
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 29
Source Project: Airbnb-Android-Google-Map-View   Source File: BaseNetwork.java    License: MIT License 4 votes vote down vote up
/**
 * For Post Method with parameters in the content body
 *
 * @param methodType   Type of network call eg, GET,POST, etc.
 * @param url          The url to hit
 * @param paramsObject JsonObject for POST request, null for GET request
 * @param requestType  Type of Network request
 */
public void getJSONObjectForRequest(int methodType, String url, JSONObject paramsObject, final int requestType) {
    if (NetworkUtil.isInternetConnected(mContext)) {
        JsonObjectRequest jsObjRequest = new JsonObjectRequest
                (methodType, url, paramsObject, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            handleResponse(response, requestType);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        handleError(error);
                    }
                }) {

            @Override
            public String getBodyContentType() {
                return "application/x-www-form-urlencoded; charset=UTF-8";
            }


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

            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();
                return params;
            }
        };
        int socketTimeout = 5000;//30 seconds - change to what you want
        RetryPolicy policy = new DefaultRetryPolicy(socketTimeout, 2, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
        jsObjRequest.setRetryPolicy(policy);
        CustomVolleyRequestQueue.getInstance(mContext).getRequestQueue().add(jsObjRequest);
    }
}
 
Example 30
Source Project: Gizwits-SmartBuld_Android   Source File: GosScheduleSiteTool.java    License: 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);
}