示例#1
0
 /**
  * 内部调用接口,发起一个通用的GsonRequest请求
  *
  * @param url 请求地址
  * @param clazz 响应的模型
  * @param success 成功的回调
  * @param error 失败的回调
  * @param name 要上传文件的字段名(可选)
  * @param file 要上传的文件(可选)
  * @param sendImmediately 是否创建请求后马上发送,如果传false,则需要自己将request加入到requestQueue中去
  * @return 返回的Request对象可以用于取消请求
  */
 public static <T> Request request(
     int method,
     String url,
     String refer,
     String name,
     File file,
     Class<T> clazz,
     Response.Listener<T> success,
     Response.ErrorListener error,
     boolean sendImmediately) {
   Request request;
   if (null == file) {
     request = new GsonRequest<T>(method, url, refer, clazz, null, null, success, error);
     request.setRetryPolicy(
         RetryPolicyFactory.getRetryPolicy(RetryPolicyFactory.RETRY_POLICY.NORMAL));
   } else {
     request = new GsonRequest<T>(method, url, refer, clazz, name, file, success, error);
     request.setRetryPolicy(
         RetryPolicyFactory.getRetryPolicy(RetryPolicyFactory.RETRY_POLICY.MULTIPART));
   }
   if (sendImmediately) {
     requestQueue.add(request);
   }
   return request;
 }
示例#2
0
  private void logParams(Request<?> request) {
    if (!OpenApi.DEBUG) return;
    try {
      StringBuffer sb = new StringBuffer();
      sb.append(request.getUrl()).append("?");
      Map<String, String> postdata = request.getParams();

      if (postdata == null) return;

      Utils.Log(
          "URL_METHOD",
          postdata.get(OpenApi.API_METHOD) == null
              ? ""
              : postdata.get(OpenApi.API_METHOD).toString());
      ;

      for (Map.Entry<String, String> item : postdata.entrySet()) {
        sb.append("").append(item.getKey()).append("=").append(item.getValue()).append("&");
        Utils.Log("URL_PARAM", item.getKey() + "=" + item.getValue());
      }
      Utils.Log("URL", sb.toString());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
示例#3
0
 @Test
 public void otherClientError() throws Exception {
   for (int i = 400; i <= 499; i++) {
     if (i == 401 || i == 403) {
       // covered above.
       continue;
     }
     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 other 400 errors.
     verify(mMockRetryPolicy, never()).retry(any(VolleyError.class));
     reset(mMockRetryPolicy);
   }
 }
示例#4
0
  /**
   * Called from {@link Request#finish(String)}, indicating that processing of the given request has
   * finished.
   *
   * <p>Releases waiting requests for <code>request.getCacheKey()</code> if <code>
   * request.shouldCache()</code>.
   *
   * <p>(1). 首先从正在进行中请求集合mCurrentRequests中移除该请求。 (2).
   * 然后查找请求等待集合mWaitingRequests中是否存在等待的请求,如果存在,则将等待队列移除,
   * 并将等待队列所有的请求添加到缓存请求队列中,让缓存请求处理线程CacheDispatcher自动处理。
   */
  <T> void finish(Request<T> request) {
    // Remove from the set of requests currently being processed.
    synchronized (mCurrentRequests) {
      mCurrentRequests.remove(request);
    }
    synchronized (mFinishedListeners) {
      for (RequestFinishedListener<T> listener : mFinishedListeners) {
        listener.onRequestFinished(request);
      }
    }

    if (request.shouldCache()) {
      synchronized (mWaitingRequests) {
        String cacheKey = request.getCacheKey();
        Queue<Request<?>> 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);
        }
      }
    }
  }
示例#5
0
  protected void modifyJiage() {

    String PriceHour, PriceMonth;

    if (MyTextUtils.isEmpty(etPriceHour.getText().toString())) {
      ToastUtils.showSuperToastComment(getApplicationContext(), "时租价格不能为空");
      return;
    } else {
      PriceHour = etPriceHour.getText().toString();
    }

    if (MyTextUtils.isEmpty(etPriceMonth.getText().toString())) {
      ToastUtils.showSuperToastComment(getApplicationContext(), "月租价格不能为空");
      return;
    } else {
      PriceMonth = etPriceMonth.getText().toString();
    }

    String url;

    url = PathConfig.ADDRESS + "/base/breleasepark/setPrice";
    url = MyTextUtils.urlPlusFoot(url);

    Map<String, String> params = new HashMap<String, String>();
    params.put("Code", detailMap.get("CODE"));
    params.put("PriceHour", PriceHour);
    params.put("PriceMonth", PriceMonth);

    Request<JSONObject> request =
        new VolleyCommonPost(
            url,
            new Response.Listener<JSONObject>() {
              @Override
              public void onResponse(JSONObject response) {
                String jsondata = response.toString();
                Map<String, String> message =
                    JSON.parseObject(jsondata, new TypeReference<Map<String, String>>() {});

                if (message.get("status").equals("true")) {
                  dismissDialog();
                  finish();
                  ToastUtils.showSuperToastAlertGreen(ModifyParkJiaGe.this, message.get("info"));
                } else {
                  ToastUtils.showSuperToastAlert(ModifyParkJiaGe.this, message.get("info"));
                  finish();
                }
              }
            },
            new Response.ErrorListener() {
              @Override
              public void onErrorResponse(VolleyError error) {
                dismissDialog();
                ToastUtils.showSuperToastAlert(ModifyParkJiaGe.this, "连接服务器失败,请稍后重试!");
              }
            },
            params);
    request.setRetryPolicy(new DefaultRetryPolicy(200 * 1000, 1, 1.0f));
    ApplicationController.getInstance().addToRequestQueue(request);
  }
  public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? "TAG" : tag);

    VolleyLog.d("Adding request to queue: %s", req.getUrl());

    getRequestQueue().add(req);
  }
示例#7
0
 /**
  * 通过GET方法下载一个文件,内部会走HTTP的缓存机制
  *
  * @param url
  * @param success
  * @param error
  * @return
  */
 public static Request<File> download(
     String url, Response.Listener<File> success, Response.ErrorListener error) {
   Request<File> request = new FileRequest(Method.GET, url, success, error);
   request.setRetryPolicy(
       RetryPolicyFactory.getRetryPolicy(RetryPolicyFactory.RETRY_POLICY.DOWNLOAD));
   requestQueue.add(request);
   return request;
 }
示例#8
0
 /**
  * Cancels all requests in this queue for which the given filter applies.
  *
  * <p>取消当前请求集合中所有符合条件的请求。 filter 参数表示可以按照自定义的过滤器过滤需要取消的请求。
  *
  * @param filter The filtering function to use
  */
 public void cancelAll(RequestFilter filter) {
   synchronized (mCurrentRequests) {
     for (Request<?> request : mCurrentRequests) {
       if (filter.apply(request)) {
         request.cancel();
       }
     }
   }
 }
 public <T> void addToRequestQueue(Request<T> req) {
   req.setTag(TAG);
   req.setRetryPolicy(
       new DefaultRetryPolicy(
           DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2,
           DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
           DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
   getRequestQueue().add(req);
 }
  @Before
  public void setUp() throws Exception {
    initMocks(this);
    dispatcher = new SyncDispatcher(cache, mockNetwork);
    Response response = Response.success(null, cacheEntry);

    when(cache.get(anyString())).thenReturn(cacheEntry);
    when(request.parseNetworkResponse(any(NetworkResponse.class))).thenReturn(response);
    when(request.getCacheKey()).thenReturn("test-cache-key");
  }
示例#11
0
 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));
     onPreStartConnection();
     fRequestQueue.add(request);
   }
 }
示例#12
0
 @SuppressWarnings("deprecation")
 /* package */ static void setConnectionParametersForRequest(
     HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError {
   switch (request.getMethod()) {
     case Method.DEPRECATED_GET_OR_POST:
       // This is the deprecated way that needs to be handled for backwards compatibility.
       // If the request's post body is null, then the assumption is that the request is
       // GET.  Otherwise, it is assumed that the request is a POST.
       byte[] postBody = request.getPostBody();
       if (postBody != null) {
         // Prepare output. There is no need to set Content-Length explicitly,
         // since this is handled by HttpURLConnection using the size of the prepared
         // output stream.
         connection.setDoOutput(true);
         connection.setRequestMethod("POST");
         connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
         DataOutputStream out = new DataOutputStream(connection.getOutputStream());
         out.write(postBody);
         out.close();
       }
       break;
     case Method.GET:
       // Not necessary to set the request method because connection defaults to GET but
       // being explicit here.
       connection.setRequestMethod("GET");
       break;
     case Method.DELETE:
       connection.setRequestMethod("DELETE");
       break;
     case Method.POST:
       connection.setRequestMethod("POST");
       addBodyIfExists(connection, request);
       break;
     case Method.PUT:
       connection.setRequestMethod("PUT");
       addBodyIfExists(connection, request);
       break;
     case Method.HEAD:
       connection.setRequestMethod("HEAD");
       break;
     case Method.OPTIONS:
       connection.setRequestMethod("OPTIONS");
       break;
     case Method.TRACE:
       connection.setRequestMethod("TRACE");
       break;
     case Method.PATCH:
       connection.setRequestMethod("PATCH");
       addBodyIfExists(connection, request);
       break;
     default:
       throw new IllegalStateException("Unknown method type.");
   }
 }
示例#13
0
 public static void searchTweet(Context context, String pUrl, NetworkCallback callback) {
   StringBuilder url = new StringBuilder(pUrl);
   url.append("&count=" + DEFAULT_PAGE_SIZE);
   Request<String> volleyTypeRequest = null;
   volleyTypeRequest =
       bundleToVolleyRequestWithSoftTtl(
           context, Request.Method.GET, null, url.toString(), callback);
   volleyTypeRequest.setTag(callback);
   volleyTypeRequest.setShouldCache(true);
   dispatchToQueue(volleyTypeRequest, context);
 }
示例#14
0
 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();
   }
 }
示例#15
0
 public static <T> void addRequest(RequestQueue requestQueue, Request<T> request, Object tag) {
   if (tag != null) {
     request.setTag(tag);
   }
   request.setShouldCache(false);
   request.setRetryPolicy(
       new DefaultRetryPolicy(
           TIME_OUT,
           DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
           DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
   requestQueue.add(request);
 }
  @SuppressWarnings("deprecation")
  private static void setConnectionParametersForRequest(
      com.squareup.okhttp.Request.Builder builder, Request<?> request)
      throws IOException, 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.getPostBody();

        if (postBody != null) {
          builder.post(
              RequestBody.create(MediaType.parse(request.getPostBodyContentType()), postBody));
        }
        break;

      case Request.Method.GET:
        builder.get();
        break;

      case Request.Method.DELETE:
        builder.delete();
        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.");
    }
  }
示例#17
0
  /**
   * 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));
  }
  @Override
  public HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    OkHttpClient client = okHttpClient.clone();
    int timeoutMs = request.getTimeoutMs();
    client.setConnectTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setReadTimeout(timeoutMs, TimeUnit.MILLISECONDS);
    client.setWriteTimeout(timeoutMs, TimeUnit.MILLISECONDS);

    com.squareup.okhttp.Request.Builder okHttpRequestBuilder =
        new com.squareup.okhttp.Request.Builder();
    okHttpRequestBuilder.url(request.getUrl());

    Map<String, String> headers = request.getHeaders();

    for (final String name : headers.keySet()) {
      okHttpRequestBuilder.addHeader(name, headers.get(name));
    }

    for (final String name : additionalHeaders.keySet()) {
      okHttpRequestBuilder.addHeader(name, additionalHeaders.get(name));
    }

    setConnectionParametersForRequest(okHttpRequestBuilder, request);

    com.squareup.okhttp.Request okHttpRequest = okHttpRequestBuilder.build();
    Call okHttpCall = client.newCall(okHttpRequest);
    Response okHttpResponse = okHttpCall.execute();

    StatusLine responseStatus =
        new BasicStatusLine(
            parseProtocol(okHttpResponse.protocol()),
            okHttpResponse.code(),
            okHttpResponse.message());

    BasicHttpResponse response = new BasicHttpResponse(responseStatus);
    response.setEntity(entityFromOkHttpResponse(okHttpResponse));

    Headers responseHeaders = okHttpResponse.headers();

    for (int i = 0, len = responseHeaders.size(); i < len; i++) {
      final String name = responseHeaders.name(i), value = responseHeaders.value(i);

      if (name != null) {
        response.addHeader(new BasicHeader(name, value));
      }
    }

    return response;
  }
 @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
 private void addTrafficStatsTag(Request<?> request) {
   // Tag the request (if API >= 14)
   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
     TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
   }
 }
  @Override
  public void deliverError(VolleyError error) {
    super.deliverError(error);
    if (mListenerReference != null && mListenerReference.get() != null) {
      NetworkListener listener = mListenerReference.get();
      BaseError response = new BaseError();

      if (error.networkResponse != null) {
        response.mStatusCode = error.networkResponse.statusCode;
        response.mErrorMessage = new String(error.networkResponse.data);
      } else if (error instanceof NetworkError || error instanceof NoConnectionError) {
        response.mErrorMessage = "Please check the internet connection";
      } else if (error instanceof TimeoutError) {
        response.mErrorMessage = "Server is busy try again later";
      } else if (error instanceof AuthFailureError) {
        response.mErrorMessage = "Auth Failure";
      } else if (error instanceof ServerError) {
        response.mErrorMessage = "ServerError";
      } else if (error instanceof ParseError) {
        response.mErrorMessage = "Error in parsing server data";
      }

      listener.onError(response);
    }
  }
示例#21
0
 @Test
 public void connectTimeout() throws Exception {
   MockHttpStack mockHttpStack = new MockHttpStack();
   mockHttpStack.setExceptionToThrow(new ConnectTimeoutException());
   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 retry connection timeouts
   verify(mMockRetryPolicy).retry(any(TimeoutError.class));
 }
 @Override
 public boolean isCancelled() {
   if (mRequest == null) {
     return false;
   }
   return mRequest.isCanceled();
 }
  @Test
  public void testRefresh() throws VolleyError {
    when(cacheEntry.isExpired()).thenReturn(false);
    when(cacheEntry.refreshNeeded()).thenReturn(true);

    // mock non expired entry for return
    Cache.Entry networkEntry = mock(Cache.Entry.class);
    when(networkEntry.isExpired()).thenReturn(false);

    Response response = Response.success(null, networkEntry);
    when(request.parseNetworkResponse(any(NetworkResponse.class))).thenReturn(response);
    request.setShouldCache(true);

    dispatcher.processRequest(request);
    verify(cache).put("test-cache-key", networkEntry);
    verify(mockNetwork).performRequest(request);
  }
  private void addToRequestQueue(Request req, String tag) {
    if (null == tag) {
      tag = requestUrlToTag.get(req.getUrl());
      if (null == tag) {
        tag = HackApplication.randomString.nextString();
        requestUrlToTag.put(req.getUrl(), tag);
      }
      req.setTag(tag);
    } else {
      req.setTag(tag);
    }

    cancelFromRequestQueue(req, tag);
    Log.e(TAG, "URL: -> " + req.getUrl());

    makaanGetRequestQueue.add(req);
  }
示例#25
0
 /**
  * 发起一个同步HTTP请求
  *
  * @param method
  * @param url
  * @param name
  * @param file
  * @param clazz
  * @return
  * @throws java.util.concurrent.ExecutionException
  * @throws InterruptedException
  */
 public static <T> T requestSync(
     int method, String url, String refer, String name, File file, Class<T> clazz)
     throws ExecutionException, InterruptedException {
   Request<T> request;
   RequestFuture<T> future = RequestFuture.newFuture();
   if (null == file) {
     request = new GsonRequest<T>(method, url, refer, clazz, null, null, future, future);
     request.setRetryPolicy(
         RetryPolicyFactory.getRetryPolicy(RetryPolicyFactory.RETRY_POLICY.NORMAL));
   } else {
     request = new GsonRequest<T>(method, url, refer, clazz, name, file, future, future);
     request.setRetryPolicy(
         RetryPolicyFactory.getRetryPolicy(RetryPolicyFactory.RETRY_POLICY.MULTIPART));
   }
   requestQueue.add(request);
   T t = future.get();
   return t;
 }
示例#26
0
  public HttpResponse performMultiPartRequest(
      Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createMultiPartRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();
    // TODO: Reevaluate this connection timeout based on more wide-scale
    // data collection and possibly different for wifi vs. 3G.
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);

    /* Make a thread safe connection manager for the client */
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    return httpClient.execute(httpRequest);
  }
  public static void addRequest(Request<?> request, Object tag) {
    if (tag != null) {
      request.setTag(tag);
    }
    mRequestQueue.add(request);

    //		Logger.d("addRequest = " + request.getUrl());

  }
示例#28
0
 @Test
 public void forbidden() throws Exception {
   MockHttpStack mockHttpStack = new MockHttpStack();
   BasicHttpResponse fakeResponse =
       new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), 403, "Forbidden");
   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 retry in case it's an auth failure.
   verify(mMockRetryPolicy).retry(any(AuthFailureError.class));
 }
示例#29
0
  /**
   * Our comparator sorts from high to low priority, and secondarily by sequence number to provide
   * FIFO ordering.
   */
  @Override
  public int compareTo(Request<T> other) {
    Priority left = this.getPriority();
    Priority right = other.getPriority();

    // High-priority requests are "lesser" so they are sorted to the front.
    // Equal priorities are sorted by sequence number to provide FIFO ordering.
    return left == right ? this.mSequence - other.mSequence : right.ordinal() - left.ordinal();
  }
示例#30
0
  public HttpResponse performMultiPartRequest(
      Request<?> request, Map<String, String> additionalHeaders)
      throws IOException, AuthFailureError {
    HttpUriRequest httpRequest = createMultiPartRequest(request, additionalHeaders);
    addHeaders(httpRequest, additionalHeaders);
    addHeaders(httpRequest, request.getHeaders());
    HttpParams httpParams = httpRequest.getParams();
    int timeoutMs = request.getTimeoutMs();

    if (timeoutMs != -1) {
      HttpConnectionParams.setSoTimeout(httpParams, timeoutMs);
    }

    /* Make a thread safe connection manager for the client */
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    return httpClient.execute(httpRequest);
  }