/**
   * Initializes the DiskBasedCache by scanning for all files currently in the specified root
   * directory. Creates the root directory if necessary.
   */
  @Override
  public synchronized void initialize() {
    if (!mRootDirectory.exists()) { // 如果根目录不存在,创建根目录
      if (!mRootDirectory.mkdirs()) {
        VolleyLog.e("Unable to create cache dir %s", mRootDirectory.getAbsolutePath());
      }
      return;
    }

    File[] files = mRootDirectory.listFiles();
    if (files == null) {
      return;
    }
    // 遍历所有的文件,将文件转换为CacheHeader对象,并将其添加到缓存集合之中
    for (File file : files) {
      FileInputStream fis = null;
      try {
        fis = new FileInputStream(file);
        CacheHeader entry = CacheHeader.readHeader(fis);
        entry.size = file.length();
        putEntry(entry.key, entry);
      } catch (IOException e) {
        if (file != null) {
          file.delete(); // 如果存在异常则删除异常文件
        }
      } finally {
        try {
          if (fis != null) {
            fis.close();
          }
        } catch (IOException ignored) {
        }
      }
    }
  }
 private void buildMultipartEntity() {
   entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
   try {
     entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
   } catch (UnsupportedEncodingException e) {
     VolleyLog.e("UnsupportedEncodingException");
   }
 }
 protected void finalize() throws Throwable {
   if (!this.mFinished) {
     finish("Request on the loose");
     VolleyLog.e(
         "Marker log finalized without finish() - uncaught exit point for request",
         new Object[0]);
   }
 }
 @Override
 public byte[] getBody() throws AuthFailureError {
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   try {
     entity.writeTo(bos);
   } catch (IOException e) {
     VolleyLog.e("IOException writing to ByteArrayOutputStream");
   }
   return bos.toByteArray();
 }
  @Override
  public byte[] getBody() throws AuthFailureError {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    try {
      entity.writeTo(bos);
    } catch (IOException e) {
      VolleyLog.e("IOException writing to ByteArrayOutputStream");
    }

    //   return bos.toByteArray();
    System.out.println("write entity:" + byteArrayGlobal.toString());
    return byteArrayGlobal;
  }
 private void buildMultipartEntity() {
   entity.addPart(
       "profile_picture",
       new FileBody(new File("/storage/emulated/0/Pictures/VSCOCam/2015-07-31 11.55.14 1.jpg")));
   try {
     entity.addPart("user_id", new StringBody("15"));
     entity.addPart("name", new StringBody("Bogs"));
     entity.addPart("gender", new StringBody("Male"));
     entity.addPart("date_birth", new StringBody("1999-12-5"));
     entity.addPart("breed", new StringBody("monkey"));
   } catch (UnsupportedEncodingException e) {
     VolleyLog.e("UnsupportedEncodingException");
   }
 }
  public MultipartRequest(
      String url,
      Response.Listener<String> rListener,
      Response.ErrorListener eListener,
      @Nullable HashMap<String, String> head,
      @NonNull String stringPart,
      @NonNull File file,
      @Nullable Map<String, Object> param) {
    super(Method.POST, url, rListener, eListener);

    header = null;
    if (head == null) {
      header = new HashMap<>();
    } else {
      header = (HashMap) head.clone();
    }

    String boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW";
    header.put("Content-Type", "multipart/form-data; boundary=" + boundary);

    // build multi-part
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setBoundary(boundary);
    entityBuilder.addPart(stringPart, new FileBody(file));
    if (param != null) {
      try {
        for (String key : param.keySet()) {
          Object obj = param.get(key);
          String input = obj.toString();
          entityBuilder.addPart(key, new StringBody(input, ContentType.MULTIPART_FORM_DATA));
        }
      } catch (Exception e) {
        VolleyLog.e("Fail to build multipart. " + e.getMessage());
        e.printStackTrace();
      }
    }
    entity = entityBuilder.build();
  }
Exemple #8
0
  private static void addColumns2Map(
      Class<?> entityType, String primaryKeyFieldName, HashMap<String, Column> columnMap) {
    if (Object.class.equals(entityType)) return;
    try {
      Field[] fields = entityType.getDeclaredFields();
      for (Field field : fields) {
        if (ColumnUtils.isTransient(field) || Modifier.isStatic(field.getModifiers())) {
          continue;
        }
        if (ColumnConverterFactory.isSupportColumnConverter(field.getType())) {
          if (!field.getName().equals(primaryKeyFieldName)) {
            Column column = new Column(entityType, field);
            if (!columnMap.containsKey(column.getColumnName())) {
              columnMap.put(column.getColumnName(), column);
            }
          }
        } else if (ColumnUtils.isForeign(field)) {
          Foreign column = new Foreign(entityType, field);
          if (!columnMap.containsKey(column.getColumnName())) {
            columnMap.put(column.getColumnName(), column);
          }
        } else if (ColumnUtils.isFinder(field)) {
          Finder column = new Finder(entityType, field);
          if (!columnMap.containsKey(column.getColumnName())) {
            columnMap.put(column.getColumnName(), column);
          }
        }
      }

      if (!Object.class.equals(entityType.getSuperclass())) {
        addColumns2Map(entityType.getSuperclass(), primaryKeyFieldName, columnMap);
      }
    } catch (Throwable e) {
      VolleyLog.e(e.getMessage(), e);
    }
  }
  @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);
        }
      }
    }
  }
  @Override
  public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    Request request;
    while (true) {
      try {
        // Take a request from the queue.
        request = mQueue.take();
      } catch (InterruptedException e) {
        // We may have been interrupted because it was time to quit.
        if (mQuit) {
          return;
        }
        continue;
      }

      try {
        request.addMarker("network-queue-take");

        // If the request was cancelled already, do not perform the
        // network request.
        if (request.isCanceled()) {
          request.finish("network-discard-cancelled");
          continue;
        }

        // Tag the request (if API >= 14)
        if (Build.VERSION.SDK_INT >= 14) {
          TrafficStats.setThreadStatsTag(request.getTrafficStatsTag());
        }

        // Perform the network request.
        NetworkResponse networkResponse = mNetwork.performRequest(request);
        request.addMarker("network-http-complete");

        // If the server returned 304 AND we delivered a response already,
        // we're done -- don't deliver a second identical response.
        if (networkResponse.notModified && request.hasHadResponseDelivered()) {
          request.finish("not-modified");
          continue;
        }

        // Parse the response here on the worker thread.
        Response<?> response = request.parseNetworkResponse(networkResponse);
        request.addMarker("network-parse-complete");

        // Write to cache if applicable.
        // TODO: Only update cache metadata instead of entire record for 304s.
        if (request.shouldCache() && response.cacheEntry != null) {
          mCache.put(request.getCacheKey(), response.cacheEntry);
          request.addMarker("network-cache-written");
        }

        // Post the response back.
        request.markDelivered();
        mDelivery.postResponse(request, response);
      } catch (VolleyError volleyError) {
        parseAndDeliverNetworkError(request, volleyError);
      } catch (Exception e) {
        VolleyLog.e(e, "Unhandled exception %s", e.toString());
        mDelivery.postError(request, new VolleyError(e));
      }
    }
  }