Java Code Examples for com.android.volley.Request
The following examples show how to use
com.android.volley.Request. 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: Volley-Ball Source File: BallRequestQueue.java License: MIT License | 6 votes |
/** * Called from {@link com.android.volley.Request#finish(String)}, indicating that processing of the given request * has finished. * <p/> * <p>Releases waiting requests for <code>request.getCacheKey()</code> if * <code>request.shouldCache()</code>.</p> */ protected void finish(Request request) { // Remove from the set of requests currently being processed. synchronized (mCurrentRequests) { mCurrentRequests.remove(request); } if (request.shouldCache()) { synchronized (mWaitingRequests) { String cacheKey = request.getCacheKey(); Queue<BallRequest> waitingRequests = mWaitingRequests.remove(cacheKey); if (waitingRequests != null) { if (VolleyLog.DEBUG) { VolleyLog.v("Releasing %d waiting requests for cacheKey=%s.", waitingRequests.size(), cacheKey); } // Process all queued up requests. They won't be considered as in flight, but // that's not a problem as the cache has been primed by 'request'. mCacheQueue.addAll(waitingRequests); } } } }
Example 2
Source Project: openshop.io-android Source File: SplashActivity.java License: MIT License | 6 votes |
/** * Load available shops from server. */ private void requestShops() { if (layoutIntroScreen.getVisibility() != View.VISIBLE) progressDialog.show(); GsonRequest<ShopResponse> getShopsRequest = new GsonRequest<>(Request.Method.GET, EndPoints.SHOPS, null, ShopResponse.class, new Response.Listener<ShopResponse>() { @Override public void onResponse(@NonNull ShopResponse response) { Timber.d("Get shops response: %s", response.toString()); setSpinShops(response.getShopList()); if (progressDialog != null) progressDialog.cancel(); animateContentVisible(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { if (progressDialog != null) progressDialog.cancel(); MsgUtils.logAndShowErrorMessage(activity, error); finish(); } }); getShopsRequest.setRetryPolicy(MyApplication.getDefaultRetryPolice()); getShopsRequest.setShouldCache(false); MyApplication.getInstance().addToRequestQueue(getShopsRequest, CONST.SPLASH_REQUESTS_TAG); }
Example 3
Source Project: JianDan Source File: RequestManager.java License: Apache License 2.0 | 6 votes |
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: volley Source File: BasicNetworkTest.java License: Apache License 2.0 | 6 votes |
@Test public void serverError_disableRetries() throws Exception { for (int i = 500; i <= 599; i++) { MockHttpStack mockHttpStack = new MockHttpStack(); HttpResponse fakeResponse = new HttpResponse(i, Collections.<Header>emptyList()); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should not retry any 500 error w/ HTTP 500 retries turned off (the default). verify(mMockRetryPolicy, never()).retry(any(VolleyError.class)); reset(mMockRetryPolicy); } }
Example 5
Source Project: android-kubernetes-blockchain Source File: ShopFragment.java License: Apache License 2.0 | 6 votes |
public void getStateOfUser(String userId, final int failedAttempts) { try { JSONObject params = new JSONObject("{\"type\":\"query\",\"queue\":\"user_queue\",\"params\":{\"userId\":\"" + userId + "\", \"fcn\":\"getState\", \"args\":[" + userId + "]}}"); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, BACKEND_URL + "/api/execute", params, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { InitialResultFromRabbit initialResultFromRabbit = gson.fromJson(response.toString(), InitialResultFromRabbit.class); if (initialResultFromRabbit.status.equals("success")) { getResultFromResultId("getStateOfUser",initialResultFromRabbit.resultId,0, failedAttempts); } else { Log.d(TAG, "Response is: " + response.toString()); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.d(TAG, "That didn't work!"); } }); queue.add(jsonObjectRequest); } catch (JSONException e) { e.printStackTrace(); } }
Example 6
Source Project: volley Source File: HurlStack.java License: Apache License 2.0 | 6 votes |
private static void addBodyIfExists(HttpURLConnection connection, final Request<?> request) throws IOException, AuthFailureError { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); if (request instanceof MultiPartRequest) { final UploadMultipartEntity multipartEntity = ((MultiPartRequest<?>) request).getMultipartEntity(); // 防止所有文件写到内存中 connection.setFixedLengthStreamingMode((int)multipartEntity.getContentLength()); multipartEntity.writeTo(connection.getOutputStream()); } else { byte[] body = request.getBody(); if (body != null) { DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } } }
Example 7
Source Project: Study_Android_Demo Source File: MainActivity.java License: Apache License 2.0 | 6 votes |
public void btnClick3(View view){ JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, "", null , new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { } }); queue.add(request); }
Example 8
Source Project: tgen Source File: OrderService.java License: Apache License 2.0 | 6 votes |
public static RpcRequest UserAddToCartByOrderId(final int orderId, final Listener<Void> listener) { RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Order/UserAddToCartByOrderId", new Response.Listener<String>() { @Override public void onResponse(String response) {if (listener != null) { listener.onResponse(null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onResponse(null); } }) { @Override public byte[] getBody() { HashMap<String, Object> msg = new HashMap<String, Object>(); msg.put("orderId", orderId); return gson.toJson(msg).getBytes(Charset.forName("UTF-8")); } }; TRpc.getQueue().add(req); return req; }
Example 9
Source Project: product-emm Source File: BasicNetworkTest.java License: Apache License 2.0 | 6 votes |
@Test public void serverError_disableRetries() throws Exception { for (int i = 500; i <= 599; i++) { MockHttpStack mockHttpStack = new MockHttpStack(); BasicHttpResponse fakeResponse = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), i, ""); mockHttpStack.setResponseToReturn(fakeResponse); BasicNetwork httpNetwork = new BasicNetwork(mockHttpStack); Request<String> request = buildRequest(); request.setRetryPolicy(mMockRetryPolicy); doThrow(new VolleyError()).when(mMockRetryPolicy).retry(any(VolleyError.class)); try { httpNetwork.performRequest(request); } catch (VolleyError e) { // expected } // should not retry any 500 error w/ HTTP 500 retries turned off (the default). verify(mMockRetryPolicy, never()).retry(any(VolleyError.class)); reset(mMockRetryPolicy); } }
Example 10
Source Project: wasp Source File: VolleyNetworkStack.java License: Apache License 2.0 | 6 votes |
private int getMethod(String method) { switch (method) { case METHOD_GET: return Request.Method.GET; case METHOD_POST: return Request.Method.POST; case METHOD_PUT: return Request.Method.PUT; case METHOD_DELETE: return Request.Method.DELETE; case METHOD_PATCH: return Request.Method.PATCH; case METHOD_HEAD: return Request.Method.HEAD; default: throw new IllegalArgumentException("Method must be DELETE,POST,PUT,GET,PATCH,HEAD"); } }
Example 11
Source Project: tgen Source File: OrderService.java License: Apache License 2.0 | 5 votes |
public static RpcRequest GetOrderDetail(final int orderId, final Listener<TOrderDetail> listener) { RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Order/GetOrderDetail", new Response.Listener<String>() { @Override public void onResponse(String response) { try { TOrderDetail result; result = BaseModule.doFromJSON(response, TOrderDetail.class); listener.onResponse(result); } catch (Exception ex) { // Log.d("ex", ex.toString()); // Log.d("jsonObject", response); listener.onResponse(null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onResponse(null); } }) { @Override public byte[] getBody() { HashMap<String, Object> msg = new HashMap<String, Object>(); msg.put("orderId", orderId); return gson.toJson(msg).getBytes(Charset.forName("UTF-8")); } }; TRpc.getQueue().add(req); return req; }
Example 12
Source Project: android-project-wo2b Source File: BasicNetwork.java License: Apache License 2.0 | 5 votes |
/** * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete. */ private void logSlowRequests(long requestLifetime, Request<?> request, byte[] responseContents, StatusLine statusLine) { if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) { VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " + "[rc=%d], [retryCount=%s]", request, requestLifetime, responseContents != null ? responseContents.length : "null", statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount()); } }
Example 13
Source Project: android-common-utils Source File: BasicNetwork.java License: Apache License 2.0 | 5 votes |
/** * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete. */ private void logSlowRequests(long requestLifetime, Request<?> request, byte[] responseContents, StatusLine statusLine) { if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) { VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " + "[rc=%d], [retryCount=%s]", request, requestLifetime, responseContents != null ? responseContents.length : "null", statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount()); } }
Example 14
Source Project: something.apk Source File: PMSendRequest.java License: MIT License | 5 votes |
public PMSendRequest(PMReplyDataRequest.PMReplyData reply, Response.Listener<PMSendResult> success, Response.ErrorListener error) { super(Constants.BASE_URL + "private.php", Request.Method.POST, success, error); addParam("action", "dosend"); if(reply.replyToPMId > 0){ addParam("prevmessageid", reply.replyToPMId); } addParam("touser", reply.replyUsername); addParam("title", encodeHtml(reply.replyTitle)); addParam("message", encodeHtml(reply.replyMessage)); addParam("parseurl", "yes"); addParam("savecopy", "yes"); addParam("iconid", 0); }
Example 15
Source Project: tgen Source File: OrderService.java License: Apache License 2.0 | 5 votes |
public static RpcRequest UserGetEZShippingStatus(final Listener<TEzShipping> listener) { RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getWebApiUrl() + "Order/UserGetEZShippingStatus", new Response.Listener<String>() { @Override public void onResponse(String response) { try { TEzShipping result; result = BaseModule.doFromJSON(response, TEzShipping.class); listener.onResponse(result); } catch (Exception ex) { // Log.d("ex", ex.toString()); // Log.d("jsonObject", response); listener.onResponse(null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onResponse(null); } }) { @Override public byte[] getBody() { return "".getBytes(Charset.forName("UTF-8")); } }; TRpc.getQueue().add(req); return req; }
Example 16
Source Project: WayHoo Source File: BasicNetwork.java License: Apache License 2.0 | 5 votes |
/** * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete. */ private void logSlowRequests(long requestLifetime, Request<?> request, byte[] responseContents, StatusLine statusLine) { if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) { VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " + "[rc=%d], [retryCount=%s]", request, requestLifetime, responseContents != null ? responseContents.length : "null", statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount()); } }
Example 17
Source Project: UPMiss Source File: AccountLoginPresenter.java License: GNU General Public License v3.0 | 5 votes |
private void login(final String url, final JSONObject json) { mRunning = true; HttpJsonObjectRequest jsonRequestObject = new HttpJsonObjectRequest(Request.Method.POST, url, json, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { RspModel<AccountRspModel> model = RspModel.fromJson(response, AccountRspModel.getRspType()); if (model == null) { callbackError(); } else { callback(model); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { callbackError(); } }).setOnFinishListener(new HttpJsonObjectRequest.OnFinishListener() { @Override public void onFinish() { mRunning = false; } }); AppPresenter.getRequestQueue().add(jsonRequestObject); }
Example 18
Source Project: android_tv_metro Source File: HurlStack.java License: Apache License 2.0 | 5 votes |
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
Example 19
Source Project: android-discourse Source File: HttpClientStack.java License: Apache License 2.0 | 5 votes |
private static void setEntityIfNonEmptyBody(HttpEntityEnclosingRequestBase httpRequest, Request<?> request) throws AuthFailureError { byte[] body = request.getBody(); if (body != null) { HttpEntity entity = new ByteArrayEntity(body); httpRequest.setEntity(entity); } }
Example 20
Source Project: volley_demo Source File: VolleyRequest.java License: Apache License 2.0 | 5 votes |
public static void RequestGet(Context context,String url, String tag, VolleyInterface vif) { MyApplication.getHttpQueues().cancelAll(tag); stringRequest = new StringRequest(Request.Method.GET,url,vif.loadingListener(),vif.errorListener()); stringRequest.setTag(tag); MyApplication.getHttpQueues().add(stringRequest); // 不写也能执行 // MyApplication.getHttpQueues().start(); }
Example 21
Source Project: volley Source File: ImageLoaderTest.java License: Apache License 2.0 | 5 votes |
@Test public void getWithCacheMiss() throws Exception { when(mImageCache.getBitmap(anyString())).thenReturn(null); ImageLoader.ImageListener listener = mock(ImageLoader.ImageListener.class); // Ask for the image to be loaded. mImageLoader.get("http://foo", listener); // Second pass to test deduping logic. mImageLoader.get("http://foo", listener); // Response callback should be called both times. verify(listener, times(2)).onResponse(any(ImageLoader.ImageContainer.class), eq(true)); // But request should be enqueued only once. verify(mRequestQueue, times(1)).add(Mockito.<Request<?>>any()); }
Example 22
Source Project: m2x-android Source File: JsonRequest.java License: MIT License | 5 votes |
public static void makeGetRequest(final Context context, String url, Map<String,String> params, JSONObject body, final ResponseListener listener, final int requestCode) { makeRequest(context, Request.Method.GET, url, params, body, listener, requestCode); }
Example 23
Source Project: Volley-Ball Source File: NetworkRequestActivity.java License: MIT License | 5 votes |
private void startRequest() { NetworkRequest request = new SampleNetworkRequest(Request.Method.GET, "http://some.url1.com", new SingleResponseListener<String>() { @Override public void onResponse(String response) { SimpleLogger.d("response from request 1: %s", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { SimpleLogger.d("error from request 1: %s", error.getMessage()); } } ); Application.getRequestQueue().add(request); SimpleLogger.d("Start request 1"); request = new SampleErrorNetworkRequest(Request.Method.GET, "http://some.url2.com", new SingleResponseListener<String>() { @Override public void onResponse(String response) { SimpleLogger.d("response from request 2: %s", response); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { SimpleLogger.d("error from request 2: %s", error.getMessage()); } } ); Application.getRequestQueue().add(request); SimpleLogger.d("Start request 2"); }
Example 24
Source Project: tgen Source File: PackageService.java License: Apache License 2.0 | 5 votes |
public static RpcRequest GetCompletedPackages(final Listener<ArrayList<TCompletedPackage>> listener) { RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getJsonRpcUrl(), new Response.Listener<String>() { @Override public void onResponse(String response) { try { ArrayList<TCompletedPackage> result; result = BaseModule.fromJSONArray(response, TCompletedPackage.class); listener.onResponse(result); } catch (Exception ex) { // Log.d("ex", ex.toString()); // Log.d("jsonObject", response); listener.onResponse(null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onResponse(null); } }) { @Override public byte[] getBody() { final ArrayList<Object> params = new ArrayList<>(); HashMap<String, Object> msg = new HashMap<>(); msg.put("id", getMsgID()); msg.put("method", "Package.GetCompletedPackages"); msg.put("params", params); return gson.toJson(msg).getBytes(Charset.forName("UTF-8")); } }; TRpc.getQueue().add(req); return req; }
Example 25
Source Project: volley_demo Source File: BasicNetwork.java License: Apache License 2.0 | 5 votes |
/** * Logs requests that took over SLOW_REQUEST_THRESHOLD_MS to complete. */ private void logSlowRequests(long requestLifetime, Request<?> request, byte[] responseContents, StatusLine statusLine) { if (DEBUG || requestLifetime > SLOW_REQUEST_THRESHOLD_MS) { VolleyLog.d("HTTP response for request=<%s> [lifetime=%d], [size=%s], " + "[rc=%d], [retryCount=%s]", request, requestLifetime, responseContents != null ? responseContents.length : "null", statusLine.getStatusCode(), request.getRetryPolicy().getCurrentRetryCount()); } }
Example 26
Source Project: android-project-wo2b Source File: HurlStack.java License: Apache License 2.0 | 5 votes |
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
Example 27
Source Project: android-discourse Source File: HurlStack.java License: Apache License 2.0 | 5 votes |
@Override public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError { String url = request.getUrl(); HashMap<String, String> map = new HashMap<String, String>(); map.putAll(request.getHeaders()); map.putAll(additionalHeaders); if (mUrlRewriter != null) { String rewritten = mUrlRewriter.rewriteUrl(url); if (rewritten == null) { throw new IOException("URL blocked by rewriter: " + url); } url = rewritten; } URL parsedUrl = new URL(url); HttpURLConnection connection = openConnection(parsedUrl, request); for (String headerName : map.keySet()) { connection.addRequestProperty(headerName, map.get(headerName)); } setConnectionParametersForRequest(connection, request); // Initialize HttpResponse with data from the HttpURLConnection. ProtocolVersion protocolVersion = new ProtocolVersion("HTTP", 1, 1); int responseCode = connection.getResponseCode(); if (responseCode == -1) { // -1 is returned by getResponseCode() if the response code could not be retrieved. // Signal to the caller that something was wrong with the connection. throw new IOException("Could not retrieve response code from HttpUrlConnection."); } StatusLine responseStatus = new BasicStatusLine(protocolVersion, connection.getResponseCode(), connection.getResponseMessage()); BasicHttpResponse response = new BasicHttpResponse(responseStatus); response.setEntity(entityFromConnection(connection)); for (Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) { if (header.getKey() != null) { Header h = new BasicHeader(header.getKey(), header.getValue().get(0)); response.addHeader(h); } } return response; }
Example 28
Source Project: tgen Source File: PackageService.java License: Apache License 2.0 | 5 votes |
public static RpcRequest GetInvoiceByPackageId(final int packageId, final Listener<TInvoice> listener) { RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getJsonRpcUrl(), new Response.Listener<String>() { @Override public void onResponse(String response) { try { TInvoice result; result = BaseModule.fromJSON(response, TInvoice.class); listener.onResponse(result); } catch (Exception ex) { // Log.d("ex", ex.toString()); // Log.d("jsonObject", response); listener.onResponse(null); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { listener.onResponse(null); } }) { @Override public byte[] getBody() { final ArrayList<Object> params = new ArrayList<>(); params.add(packageId); HashMap<String, Object> msg = new HashMap<>(); msg.put("id", getMsgID()); msg.put("method", "Package.GetInvoiceByPackageId"); msg.put("params", params); return gson.toJson(msg).getBytes(Charset.forName("UTF-8")); } }; TRpc.getQueue().add(req); return req; }
Example 29
Source Project: CrossBow Source File: HurlStack.java License: Apache License 2.0 | 5 votes |
private static void addBodyIfExists(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { byte[] body = request.getBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.close(); } }
Example 30
Source Project: something.apk Source File: PMReplyDataRequest.java License: MIT License | 5 votes |
@Override public PMReplyData parseHtmlResponse(Request<PMReplyData> request, NetworkResponse response, Document document) throws Exception { int pmId = 0; String id = document.getElementsByAttributeValue("name", "prevmessageid").val(); if(id != null && id.matches("\\d+")){ pmId = Integer.parseInt(id); } String username = document.getElementsByAttributeValue("name", "touser").val(); String replyContent = document.getElementsByAttributeValue("name", "message").text(); String title = document.getElementsByAttributeValue("name", "title").val(); return new PMReplyData(pmId, unencodeHtml(replyContent), username, unencodeHtml(title)); }