Example #1
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();
    }
  }
  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);
  }
  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);
  }
 private void cancelFromRequestQueue(Request req, String tag) {
   if (null != makaanGetRequestQueue) {
     if (tag == null && null != req) {
       tag = requestUrlToTag.get(req.getUrl());
       makaanGetRequestQueue.cancelAll(tag);
     } else if (null != tag) {
       makaanGetRequestQueue.cancelAll(tag);
     }
   }
 }
Example #5
0
 static HttpUriRequest createMultiPartRequest(
     Request<?> request, Map<String, String> additionalHeaders) throws 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.getBody();
         if (postBody != null) {
           HttpPost postRequest = new HttpPost(request.getUrl());
           if (request.getBodyContentType() != null)
             postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
           HttpEntity entity;
           entity = new ByteArrayEntity(postBody);
           postRequest.setEntity(entity);
           return postRequest;
         } else {
           return new HttpGet(request.getUrl());
         }
       }
     case Method.GET:
       return new HttpGet(request.getUrl());
     case Method.DELETE:
       return new HttpDelete(request.getUrl());
     case Method.POST:
       {
         HttpPost postRequest = new HttpPost(request.getUrl());
         if (request.getBodyContentType() != null) {
           postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         }
         setMultiPartBody(postRequest, request);
         return postRequest;
       }
     case Method.PUT:
       {
         HttpPut putRequest = new HttpPut(request.getUrl());
         if (request.getBodyContentType() != null)
           putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         setMultiPartBody(putRequest, request);
         return putRequest;
       }
       // Added in source code of Volley libray.
     case Method.PATCH:
       {
         HttpPatch patchRequest = new HttpPatch(request.getUrl());
         if (request.getBodyContentType() != null)
           patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
         return patchRequest;
       }
     default:
       throw new IllegalStateException("Unknown request method.");
   }
 }
  @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;
  }
Example #7
0
 @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);
   if (hasResponseBody(request.getMethod(), responseStatus.getStatusCode())) {
     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 #8
0
  @Override
  public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
      HttpResponse httpResponse = null;
      byte[] responseContents = null;
      Map<String, String> responseHeaders = new HashMap<String, String>();
      try {
        // Log Params
        logParams(request);
        // Gather headers.
        Map<String, String> headers = new HashMap<String, String>();

        headers.put("Accept-Encoding", "gzip");
        headers.put("Connection", "Keep-Alive");

        addCacheHeaders(headers, request.getCacheEntry());
        httpResponse = mHttpStack.performRequest(request, headers);

        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        responseHeaders = convertHeaders(httpResponse.getAllHeaders());
        // Handle cache validation.
        if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
          return new NetworkResponse(
              HttpStatus.SC_NOT_MODIFIED, request.getCacheEntry().data, responseHeaders, true);
        }

        //                responseContents = entityToBytes(httpResponse.getEntity());
        responseContents = entityToBytes(httpResponse);
        // if the request is slow, log it.
        long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
        logSlowRequests(requestLifetime, request, responseContents, statusLine);

        if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_NO_CONTENT) {
          throw new IOException();
        }
        return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
      } catch (SocketTimeoutException e) {
        //            	e.printStackTrace();
        if (!request.allowRetry()) return null;
        attemptRetryOnException("socket", request, new TimeoutError());
      } catch (ConnectTimeoutException e) {
        //            	e.printStackTrace();
        if (!request.allowRetry()) return null;
        attemptRetryOnException("connection", request, new TimeoutError());
      } catch (MalformedURLException e) {
        //            	e.printStackTrace();
        throw new RuntimeException("Bad URL " + request.getUrl(), e);
      } catch (IOException e) {
        //            	e.printStackTrace();
        if (!request.allowRetry()) return null;
        int statusCode = 0;
        NetworkResponse networkResponse = null;
        if (httpResponse != null) {
          statusCode = httpResponse.getStatusLine().getStatusCode();
        } else {
          throw new NoConnectionError(e);
        }
        VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
        if (responseContents != null) {
          networkResponse =
              new NetworkResponse(statusCode, responseContents, responseHeaders, false);
          if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
            attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
          } else {
            // TODO: Only throw ServerError for 5xx status codes.
            throw new ServerError(networkResponse);
          }
        } else {
          throw new NetworkError(networkResponse);
        }
      }
    }
  }
  @Override
  public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
      HttpResponse httpResponse = null;
      byte[] responseContents = null;
      Map<String, String> responseHeaders = new HashMap<String, String>();
      try {
        // Gather headers.
        Map<String, String> headers = new HashMap<String, String>();
        addCacheHeaders(headers, request.getCacheEntry());
        httpResponse = mHttpStack.performRequest(request, headers);
        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        responseHeaders = convertHeaders(httpResponse.getAllHeaders());
        // Handle cache validation.
        if (statusCode == HttpStatus.SC_NOT_MODIFIED) {
          return new NetworkResponse(
              HttpStatus.SC_NOT_MODIFIED,
              request.getCacheEntry() == null ? null : request.getCacheEntry().data,
              responseHeaders,
              true);
        }

        // Some responses such as 204s do not have content.  We must check.
        if (httpResponse.getEntity() != null) {
          responseContents = entityToBytes(httpResponse.getEntity());
        } else {
          // Add 0 byte response as a way of honestly representing a
          // no-content request.
          responseContents = new byte[0];
        }

        // if the request is slow, log it.
        long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
        logSlowRequests(requestLifetime, request, responseContents, statusLine);

        if (statusCode < 200 || statusCode > 299) {
          throw new IOException();
        }
        return new NetworkResponse(statusCode, responseContents, responseHeaders, false);
      } catch (SocketTimeoutException e) {
        attemptRetryOnException("socket", request, new TimeoutError());
      } catch (ConnectTimeoutException e) {
        attemptRetryOnException("connection", request, new TimeoutError());
      } catch (MalformedURLException e) {
        throw new RuntimeException("Bad URL " + request.getUrl(), e);
      } catch (IOException e) {
        int statusCode = 0;
        NetworkResponse networkResponse = null;
        if (httpResponse != null) {
          statusCode = httpResponse.getStatusLine().getStatusCode();
        } else {
          throw new NoConnectionError(e);
        }
        VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
        if (responseContents != null) {
          networkResponse =
              new NetworkResponse(statusCode, responseContents, responseHeaders, false);
          if (statusCode == HttpStatus.SC_UNAUTHORIZED || statusCode == HttpStatus.SC_FORBIDDEN) {
            attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
          } else {
            // TODO: Only throw ServerError for 5xx status codes.
            throw new ServerError(networkResponse);
          }
        } else {
          throw new NetworkError(networkResponse);
        }
      }
    }
  }
  @Override
  public NetworkResponse performRequest(Request<?> request) throws VolleyError {
    long requestStart = SystemClock.elapsedRealtime();
    while (true) {
      HttpResponse httpResponse = null;
      byte[] responseContents = null;
      Map<String, String> responseHeaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
      try {
        // Gather headers.
        Map<String, String> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        addCacheHeaders(headers, request.getCacheEntry());
        httpResponse = mHttpStack.performRequest(request, headers);
        responseHeaders.putAll(httpResponse.getAllHeaders());
        int statusCode = httpResponse.getResponseCode();

        // Handle cache validation.
        if (statusCode == HttpResponse.SC_NOT_MODIFIED) {

          Entry entry = request.getCacheEntry();
          if (entry == null) {
            return new NetworkResponse(
                HttpResponse.SC_NOT_MODIFIED,
                null,
                responseHeaders,
                true,
                SystemClock.elapsedRealtime() - requestStart);
          }

          // A HTTP 304 response does not have all header fields. We
          // have to use the header fields from the cache entry plus
          // the new ones from the response.
          // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3.5
          entry.responseHeaders.putAll(responseHeaders);
          return new NetworkResponse(
              HttpResponse.SC_NOT_MODIFIED,
              entry.data,
              entry.responseHeaders,
              true,
              SystemClock.elapsedRealtime() - requestStart);
        }

        // Handle moved resources
        if (statusCode == HttpResponse.SC_MOVED_PERMANENTLY
            || statusCode == HttpResponse.SC_MOVED_TEMPORARILY) {
          String newUrl = responseHeaders.get("Location");
          request.setRedirectUrl(newUrl);
        }

        // Some responses such as 204s do not have content.  We must check.
        if (httpResponse.getEntity() != null) {
          responseContents = entityToBytes(httpResponse.getEntity());
        } else {
          // Add 0 byte response as a way of honestly representing a
          // no-content request.
          responseContents = new byte[0];
        }

        // if the request is slow, log it.
        long requestLifetime = SystemClock.elapsedRealtime() - requestStart;
        logSlowRequests(requestLifetime, request, responseContents, httpResponse);

        if (statusCode < 200 || statusCode > 299) {
          throw new IOException();
        }
        return new NetworkResponse(
            statusCode,
            responseContents,
            responseHeaders,
            false,
            SystemClock.elapsedRealtime() - requestStart);
      } catch (SocketTimeoutException e) {
        attemptRetryOnException("socket", request, new TimeoutError());
      } catch (ConnectTimeoutException e) {
        attemptRetryOnException("connection", request, new TimeoutError());
      } catch (MalformedURLException e) {
        throw new RuntimeException("Bad URL " + request.getUrl(), e);
      } catch (IOException e) {
        int statusCode = 0;
        NetworkResponse networkResponse = null;
        if (httpResponse != null) {
          statusCode = httpResponse.getResponseCode();
        } else {
          throw new NoConnectionError(e);
        }
        if (statusCode == HttpResponse.SC_MOVED_PERMANENTLY
            || statusCode == HttpResponse.SC_MOVED_TEMPORARILY) {
          VolleyLog.e(
              "Request at %s has been redirected to %s", request.getOriginUrl(), request.getUrl());
        } else {
          VolleyLog.e("Unexpected response code %d for %s", statusCode, request.getUrl());
        }
        if (responseContents != null) {
          networkResponse =
              new NetworkResponse(
                  statusCode,
                  responseContents,
                  responseHeaders,
                  false,
                  SystemClock.elapsedRealtime() - requestStart);
          if (statusCode == HttpResponse.SC_UNAUTHORIZED
              || statusCode == HttpResponse.SC_FORBIDDEN) {
            attemptRetryOnException("auth", request, new AuthFailureError(networkResponse));
          } else if (statusCode == HttpResponse.SC_MOVED_PERMANENTLY
              || statusCode == HttpResponse.SC_MOVED_TEMPORARILY) {
            attemptRetryOnException("redirect", request, new RedirectError(networkResponse));
          } else {
            // TODO: Only throw ServerError for 5xx status codes.
            throw new ServerError(networkResponse);
          }
        } else {
          throw new NetworkError(e);
        }
      }
    }
  }