com.android.volley.Request Java Examples

The following examples show how to use com.android.volley.Request. 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: BasicNetworkTest.java    From product-emm with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: ShopFragment.java    From android-kubernetes-blockchain with Apache License 2.0 6 votes vote down vote up
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 #3
Source File: HurlStack.java    From volley with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: MainActivity.java    From Study_Android_Demo with Apache License 2.0 6 votes vote down vote up
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 #5
Source File: BasicNetworkTest.java    From volley with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: OrderService.java    From tgen with Apache License 2.0 6 votes vote down vote up
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 #7
Source File: VolleyNetworkStack.java    From wasp with Apache License 2.0 6 votes vote down vote up
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 #8
Source File: RequestManager.java    From JianDan with 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 #9
Source File: SplashActivity.java    From openshop.io-android with MIT License 6 votes vote down vote up
/**
 * 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 #10
Source File: BallRequestQueue.java    From Volley-Ball with MIT License 6 votes vote down vote up
/**
 * 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 #11
Source File: HaikuClient.java    From gplus-haiku-client-android with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieve an individual haiku from the API.
 *
 * @param haikuId the opaque identifier for a haiku
 * @param listener the object to be called when the call is complete
 */
public void fetchHaiku(final String haikuId, final HaikuRetrievedListener listener) {
    RequestQueue rq = mVolley.getRequestQueue();
    String path = GET_HAIKU.replace("{haiku_id}", haikuId);
    HaikuApiRequest<Haiku> haikuGet = new HaikuApiRequest<Haiku>(
            (new TypeToken<Haiku>() {
            }),
            Request.Method.GET,
            Constants.SERVER_URL + path,
            new Response.Listener<Haiku>() {
                @Override
                public void onResponse(Haiku data) {
                    listener.onHaikuRetrieved(data);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.d(TAG, "Retrieve haiku error");
                    if (listener != null) {
                        listener.onHaikuRetrieved(null);
                    }
                }
            },
            true
    );
    haikuGet.setTag(GET_HAIKU);
    if (mHaikuSession != null) {
        haikuGet.setSession(mHaikuSession);
    }
    rq.add(haikuGet);
}
 
Example #12
Source File: BasicNetwork.java    From android-common-utils with Apache License 2.0 5 votes vote down vote up
/**
 * 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 File: JsonRequest.java    From m2x-android with MIT License 5 votes vote down vote up
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 #14
Source File: MockNetwork.java    From SaveVolley with Apache License 2.0 5 votes vote down vote up
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    if (mNumExceptionsToThrow > 0 || mNumExceptionsToThrow == ALWAYS_THROW_EXCEPTIONS) {
        if (mNumExceptionsToThrow != ALWAYS_THROW_EXCEPTIONS) {
            mNumExceptionsToThrow--;
        }
        throw new ServerError();
    }

    requestHandled = request;
    return new NetworkResponse(mDataToReturn);
}
 
Example #15
Source File: NetworkRequestActivity.java    From Volley-Ball with MIT License 5 votes vote down vote up
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 #16
Source File: VolleyOkHttp3Stack.java    From Hentoid with Apache License 2.0 5 votes vote down vote up
private static void setConnectionParametersForRequest(okhttp3.Request.Builder builder, Request<?> request)
        throws AuthFailureError {
    switch (request.getMethod()) {
        case Request.Method.DEPRECATED_GET_OR_POST:
            // Ensure backwards compatibility.  Volley assumes a request with a null body is a GET.
            byte[] postBody = request.getBody();
            if (postBody != null) {
                builder.post(RequestBody.create(postBody, MediaType.parse(request.getBodyContentType())));
            }
            break;
        case Request.Method.GET:
            builder.get();
            break;
        case Request.Method.DELETE:
            builder.delete(createRequestBody(request));
            break;
        case Request.Method.POST:
            builder.post(createRequestBody(request));
            break;
        case Request.Method.PUT:
            builder.put(createRequestBody(request));
            break;
        case Request.Method.HEAD:
            builder.head();
            break;
        case Request.Method.OPTIONS:
            builder.method("OPTIONS", null);
            break;
        case Request.Method.TRACE:
            builder.method("TRACE", null);
            break;
        case Request.Method.PATCH:
            builder.patch(createRequestBody(request));
            break;
        default:
            throw new IllegalStateException("Unknown method type.");
    }
}
 
Example #17
Source File: BasicNetwork.java    From WayHoo with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #18
Source File: ShipfForMeService.java    From tgen with Apache License 2.0 5 votes vote down vote up
public static RpcRequest UserSendToTelephone(final String phoneNumber, final Listener<Boolean> listener) {
    RpcRequest req = new RpcRequest(Request.Method.POST, TRpc.getJsonRpcUrl(),
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Boolean result;
                    result = BaseModule.fromJSON(response, Boolean.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(phoneNumber);

            HashMap<String, Object> msg = new HashMap<>();
            msg.put("id", getMsgID());
            msg.put("method", "ShipfForMe.UserSendToTelephone");
            msg.put("params", params);

            return gson.toJson(msg).getBytes(Charset.forName("UTF-8"));
        }
    };
    TRpc.getQueue().add(req);
    return req;
}
 
Example #19
Source File: PackageService.java    From tgen with Apache License 2.0 5 votes vote down vote up
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 #20
Source File: ExtHttpClientStack.java    From android_volley_examples with Apache License 2.0 5 votes vote down vote up
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 #21
Source File: BasicNetwork.java    From volley_demo with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #22
Source File: HurlStack.java    From android-project-wo2b with Apache License 2.0 5 votes vote down vote up
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 #23
Source File: HurlStack.java    From android-discourse with Apache License 2.0 5 votes vote down vote up
@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 #24
Source File: PackageService.java    From tgen with Apache License 2.0 5 votes vote down vote up
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 #25
Source File: HurlStack.java    From CrossBow with Apache License 2.0 5 votes vote down vote up
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 #26
Source File: PMReplyDataRequest.java    From something.apk with MIT License 5 votes vote down vote up
@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));
}
 
Example #27
Source File: BasicNetwork.java    From product-emm with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to prepare the request for a retry. If there are no more attempts remaining in the
 * request's retry policy, a timeout exception is thrown.
 * @param request The request to use.
 */
private static void attemptRetryOnException(String logPrefix, Request<?> request,
        VolleyError exception) throws VolleyError {
    RetryPolicy retryPolicy = request.getRetryPolicy();
    int oldTimeout = request.getTimeoutMs();

    try {
        retryPolicy.retry(exception);
    } catch (VolleyError e) {
        request.addMarker(
                String.format("%s-timeout-giveup [timeout=%s]", logPrefix, oldTimeout));
        throw e;
    }
    request.addMarker(String.format("%s-retry [timeout=%s]", logPrefix, oldTimeout));
}
 
Example #28
Source File: MainActivity.java    From volley_demo with Apache License 2.0 5 votes vote down vote up
private void volley_getJson()
    {
        textview.setText("get Json开始了");
        // 错误url:String url = "ip.taobao.com/service/getIpInfo.php?ip=202.96.128.166"
        String url = "http://ip.taobao.com/service/getIpInfo.php?ip=202.96.128.166";
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url,
                new Response.Listener<JSONObject>()
                {
                    @Override
                    public void onResponse(JSONObject response) {
                        textview.setText(response.toString());
//                        Toast.makeText(MainActivity.this,response, Toast.LENGTH_SHORT).show();
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
//                        Toast.makeText(MainActivity.this,error.toString(), Toast.LENGTH_SHORT).show();
                        textview.setText(error.toString());
                    }


                }
        );

        requestTag = "volley_getjson";
        request.setTag(requestTag);
        MyApplication.getHttpQueues().add(request);
    }
 
Example #29
Source File: HurlStack.java    From jus with Apache License 2.0 5 votes vote down vote up
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 File: MainActivity.java    From example with Apache License 2.0 5 votes vote down vote up
private void getTickerData(String URL) {
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            URL, null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject jsonObject) {
                    progressDialog.dismiss();
                    Log.d("debug", "data -> " + jsonObject.toString());
                    // parsing data json menggunakan GSON
                    try {
                        ticker = new Gson().fromJson(jsonObject.getJSONObject("ticker").toString(), Ticker.class);
                        // tampilkan data
                        showDataTicker(ticker);
                    } catch (JSONException e) {
                        // error
                        e.printStackTrace();
                    }

                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    // errror
                    progressDialog.dismiss();
                }
            });
    progressDialog.show();
    BaseApplication.getInstance().addToRequestQueue(request, "tag");
}