Esempio n. 1
0
 @Test
 public void changeBodyTest() throws Exception {
   HttpURLConnection httpCon =
       getConnection(
           "http://localhost:8080/test/application/api?__type=14&__moduleName=TestHttpContext&__methodName=changeBody");
   checkResponceCode(httpCon);
   assertEquals(httpCon.getContentLength(), 683);
   String type = httpCon.getContentType();
   String charset = "";
   String[] values = type.split(";");
   for (String value : values) {
     if (value.toLowerCase().startsWith("charset=")) {
       charset = value.substring("charset=".length());
     }
   }
   charset = charset.isEmpty() ? "utf-8" : charset;
   String text =
       new String(
           BinaryUtils.readStream(httpCon.getInputStream(), httpCon.getContentLength()), charset);
   assertEquals(
       text,
       "Фишер: \"В 1970 году в Бледе я принял участие в международном \n"
           + "блицтурнире. В партии с Петросяном мы то и дело обменивались шахами, причем он произносил \n"
           + "это слово по-русски, а я – по-английски. В момент, когда у обоих уже начали зависать флажки,\n"
           + "я вдруг сказал по-русски: \"Вам шах, гроссмейстер!\" Петросян настолько поразился, что на какой-то \n"
           + "момент забыл о флажке и просрочил время.");
 }
  private void loadRmoteImage(String imgUrl) {
    URL fileURL = null;

    try {
      fileURL = new URL(imgUrl);
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }
    try {
      HttpURLConnection conn = (HttpURLConnection) fileURL.openConnection();
      conn.setDoInput(true);
      conn.connect();
      InputStream is = conn.getInputStream();
      int length = (int) conn.getContentLength();
      if (length != -1) {
        byte[] imgData = new byte[length];
        byte[] buffer = new byte[512];
        int readLen = 0;
        int destPos = 0;
        while ((readLen = is.read(buffer)) > 0) {
          System.arraycopy(buffer, 0, imgData, destPos, readLen);
          destPos += readLen;
        }
        bitmap = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
      }

    } catch (IOException e) {

      e.printStackTrace();
      sendMessageToHandler(2);
      return;
    }
    if (bitmap != null) sendMessageToHandler(1);
  }
Esempio n. 3
0
    public void getFileInfo() {
      myMessage.stateChanged("DOWNLOADFILEINFO");
      URL url;
      try {
        url = new URL(myProperties.getProperty("DOWNLOADURL"));
        System.out.println(myProperties.getProperty("DOWNLOADURL"));
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int contentLength = httpConn.getContentLength();
        Map<String, List<String>> theMap = httpConn.getHeaderFields();
        Set keys = theMap.keySet();
        for (Iterator i = keys.iterator(); i.hasNext(); ) {
          String key = (String) i.next();
          String value = theMap.get(key).toString();
          myMessage.messageChanged(key + " = " + value);
        }

        if (contentLength == -1) {
          myMessage.messageChanged("unknown content length");
        } else {
          myMessage.messageChanged("content length: " + contentLength + " bytes");
        }
      } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
Esempio n. 4
0
  /**
   * * 下载文件
   *
   * @return
   * @throws MalformedURLException
   */
  public void downloadUpdateFile(String down_url, String file) throws Exception {
    int down_step = 5; // 提示step
    int totalSize;
    int downloadCount = 0; // 已经下载好的大小
    InputStream inputStream;
    OutputStream outputStream;

    URL url = new URL(down_url);
    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setConnectTimeout(TIMEOUT);
    httpURLConnection.setReadTimeout(TIMEOUT);
    // 获取下载文件的size
    totalSize = httpURLConnection.getContentLength();
    if (httpURLConnection.getResponseCode() == 404) {
      throw new Exception("fail!");
    }
    inputStream = httpURLConnection.getInputStream();
    outputStream = new FileOutputStream(file, false); // 文件存在则覆盖掉
    byte buffer[] = new byte[1024];
    int readsize = 0;
    while ((readsize = inputStream.read(buffer)) != -1) {
      outputStream.write(buffer, 0, readsize);
      totalSize += readsize; // 时时获取下载到的大小

      /** 没 */
      if (downloadCount == 0 || (totalSize * 100 / totalSize - down_step) > downloadCount) {}
    }
  }
Esempio n. 5
0
 /**
  * 描述:获取网络文件的大小.
  *
  * @param Url 图片的网络路径
  * @return int 网络文件的大小
  */
 public static int getContentLengthFromUrl(String Url) {
   int mContentLength = 0;
   try {
     URL url = new URL(Url);
     HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
     mHttpURLConnection.setConnectTimeout(5 * 1000);
     mHttpURLConnection.setRequestMethod("GET");
     mHttpURLConnection.setRequestProperty(
         "Accept",
         "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
     mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
     mHttpURLConnection.setRequestProperty("Referer", Url);
     mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
     mHttpURLConnection.setRequestProperty(
         "User-Agent",
         "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
     mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
     mHttpURLConnection.connect();
     if (mHttpURLConnection.getResponseCode() == 200) {
       // 根据响应获取文件大小
       mContentLength = mHttpURLConnection.getContentLength();
     }
   } catch (Exception e) {
     e.printStackTrace();
     AbLogUtil.d(AbFileUtil.class, "获取长度异常:" + e.getMessage());
   }
   return mContentLength;
 }
  /**
   * Download a gzipped file using an HttpURLConnection, and gunzip it to the given destination.
   *
   * @param url URL to download from
   * @param destinationFile File to save the download as, including path
   * @return True if response received, destinationFile opened, and unzip successful
   * @throws IOException
   */
  private boolean downloadGzippedFileHttp(URL url, File destinationFile) throws IOException {
    // Send an HTTP GET request for the file
    Log.d(TAG, "Sending GET request to " + url + "...");
    publishProgress("Downloading data for " + languageName + "...", "0");
    HttpURLConnection urlConnection = null;
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setInstanceFollowRedirects(true);
    urlConnection.setRequestMethod("GET");
    urlConnection.connect();
    if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
      Log.e(TAG, "Did not get HTTP_OK response.");
      Log.e(TAG, "Response code: " + urlConnection.getResponseCode());
      Log.e(TAG, "Response message: " + urlConnection.getResponseMessage().toString());
      return false;
    }
    int fileSize = urlConnection.getContentLength();
    InputStream inputStream = urlConnection.getInputStream();
    File tempFile = new File(destinationFile.toString() + ".gz.download");

    // Stream the file contents to a local file temporarily
    Log.d(TAG, "Streaming download to " + destinationFile.toString() + ".gz.download...");
    final int BUFFER = 8192;
    FileOutputStream fileOutputStream = null;
    Integer percentComplete;
    int percentCompleteLast = 0;
    try {
      fileOutputStream = new FileOutputStream(tempFile);
    } catch (FileNotFoundException e) {
      Log.e(TAG, "Exception received when opening FileOutputStream.", e);
    }
    int downloaded = 0;
    byte[] buffer = new byte[BUFFER];
    int bufferLength = 0;
    while ((bufferLength = inputStream.read(buffer, 0, BUFFER)) > 0) {
      fileOutputStream.write(buffer, 0, bufferLength);
      downloaded += bufferLength;
      percentComplete = (int) ((downloaded / (float) fileSize) * 100);
      if (percentComplete > percentCompleteLast) {
        publishProgress("Downloading data for " + languageName + "...", percentComplete.toString());
        percentCompleteLast = percentComplete;
      }
    }
    fileOutputStream.close();
    if (urlConnection != null) {
      urlConnection.disconnect();
    }

    // Uncompress the downloaded temporary file into place, and remove the temporary file
    try {
      Log.d(TAG, "Unzipping...");
      gunzip(tempFile, new File(tempFile.toString().replace(".gz.download", "")));
      return true;
    } catch (FileNotFoundException e) {
      Log.e(TAG, "File not available for unzipping.");
    } catch (IOException e) {
      Log.e(TAG, "Problem unzipping file.");
    }
    return false;
  }
Esempio n. 7
0
 public static int getContentLength(String httpUrl) throws IOException, URISyntaxException {
   HttpURLConnection conn = openConnection(httpUrl);
   conn.setRequestMethod("HEAD");
   int length = conn.getContentLength();
   conn.disconnect();
   return length;
 }
 /**
  * Images proxy to be able to load images from the map
  *
  * @param encoding
  * @param cache
  * @param modified
  * @param match
  * @param url
  * @return
  */
 @GET
 @Path("image-proxy")
 @Produces("image/*")
 public Response getThumbnail(
     @HeaderParam("Accept-Encoding") String encoding,
     @HeaderParam("If-Modified-Since") String cache,
     @HeaderParam("If-Modified-Since") String modified,
     @HeaderParam("If-None-Match") String match,
     @QueryParam("url") String url) {
   UrlHelper urlHelper = new UrlHelper(url);
   try {
     urlHelper.addHeader("Accept-Encoding", encoding);
     urlHelper.addHeader("If-Modified-Since", modified);
     urlHelper.addHeader("If-None-Match", match);
     urlHelper.addHeader("Cache-Control", cache);
     urlHelper.openConnections();
     HttpURLConnection connection = (HttpURLConnection) urlHelper.getConnection();
     String tag = connection.getHeaderField("Etag");
     if (tag == null) tag = "";
     if (tag.startsWith("\"")) tag = tag.substring(1);
     if (tag.endsWith("\"")) tag = tag.substring(0, tag.length() - 1);
     return Response.ok(urlHelper.getStream(), urlHelper.getContentType())
         .lastModified(new Date(connection.getLastModified()))
         .tag(tag)
         .status(connection.getResponseCode())
         .header("Content-Length", connection.getContentLength())
         .build();
   } catch (Exception e) {
     Response.status(Responses.NOT_FOUND);
   }
   return null;
 }
Esempio n. 9
0
 public static long getFileSize(String sURL) {
   int nFileLength = -1;
   try {
     URL url = new URL(sURL);
     HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
     httpConnection.setRequestProperty("User-Agent", "Internet Explorer");
     int responseCode = httpConnection.getResponseCode();
     if (responseCode >= 400) {
       System.err.println("Error Code : " + responseCode);
       return -2; // -2 represent access is error
     }
     System.out.println(httpConnection.getContentLength());
     String sHeader;
     for (int i = 1; ; i++) {
       sHeader = httpConnection.getHeaderFieldKey(i);
       if (sHeader != null) {
         if (sHeader.equals("Content-Length")) {
           nFileLength = Integer.parseInt(httpConnection.getHeaderField(sHeader));
           break;
         }
       } else break;
     }
   } catch (IOException e) {
     e.printStackTrace();
   } catch (Exception e) {
     e.printStackTrace();
   }
   System.out.println(nFileLength);
   return nFileLength;
 }
  @Override
  protected Integer doInBackground(URL... urls) {
    // TODO Auto-generated method stub
    // URLConnection uconn = null;
    // String contentLengthStr = null;
    Integer lengthOfFile = null;
    try {
      // uconn = urls[0].openConnection();
      // uconn.setReadTimeout(2000);
      // uconn.setConnectTimeout(4000);
      HttpURLConnection connection = (HttpURLConnection) urls[0].openConnection();
      connection.setRequestMethod("HEAD");
      if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        lengthOfFile = connection.getContentLength();
        connection.disconnect();
      }
      /*try
      {
      	//uconn.connect();
      	//contentLengthStr=uconn.getHeaderField("content-length");

      }*/
    } catch (MalformedURLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    return lengthOfFile;
  }
    @Override
    public boolean hasEntity() {
      if (method.equals("HEAD") || getEntityInputStream() == null) return false;

      int l = uc.getContentLength();
      return l > 0 || l == -1;
    }
  @Override
  public void actionPerformed(ActionEvent arg0) {
    try {

      URL url = new URL(excelUrl);
      HttpURLConnection connection = (HttpURLConnection) url.openConnection();
      int filesize = connection.getContentLength();
      float totalDataRead = 0;
      java.io.BufferedInputStream in = new java.io.BufferedInputStream(connection.getInputStream());
      java.io.FileOutputStream fos = new java.io.FileOutputStream(excelName);
      java.io.BufferedOutputStream bout = new BufferedOutputStream(fos, 14921);
      byte[] data = new byte[14921];
      int i = 0;
      JOptionPane jop2 = new JOptionPane("VitalHealth Test Automation Framework");
      JDialog k2 = jop2.createDialog("Please wait till file is downloaded");
      k2.setModal(false);
      k2.setVisible(true);

      while ((i = in.read(data, 0, 14921)) >= 0) {
        totalDataRead = totalDataRead + i;
        bout.write(data, 0, i);
        float Percent = (totalDataRead * 100) / filesize;
      }
      bout.close();
      in.close();
      // fos.close();
      k2.dispose();

    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "Sample Configuration file downloaded");
    }
  }
  protected byte[] retrieveImageData() throws IOException {
    URL url = new URL(imageUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    //        connection.setRequestProperty("Authorization", "Basic "+ "bm9xc3RvcmU6dHJpYWw=");

    // determine the image size and allocate a buffer
    int fileSize = connection.getContentLength();
    if (fileSize <= 0) {
      fileSize = defaultBufferSize;
      Log.w(
          LOG_TAG,
          "Server did not set a Content-Length header, will default to buffer size of "
              + defaultBufferSize
              + " bytes");
    }
    byte[] imageData = new byte[fileSize];

    // download the file
    Log.d(LOG_TAG, "fetching image " + imageUrl + " (" + fileSize + ")");
    BufferedInputStream istream = new BufferedInputStream(connection.getInputStream());
    int bytesRead = 0;
    int offset = 0;
    while (bytesRead != -1 && offset < fileSize) {
      bytesRead = istream.read(imageData, offset, fileSize - offset);
      offset += bytesRead;
    }

    // clean up
    istream.close();
    connection.disconnect();

    return imageData;
  }
Esempio n. 14
0
  public static void downloadFile(String fileUrl, File directory) {
    FileOutputStream fileOutputStream = null;
    try {
      URL url = new URL(fileUrl);
      HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
      // urlConnection.setRequestMethod("GET");
      // urlConnection.setDoOutput(true);
      urlConnection.connect();

      InputStream inputStream = urlConnection.getInputStream();
      fileOutputStream = new FileOutputStream(directory);
      int totalSize = urlConnection.getContentLength();

      byte[] buffer = new byte[MEGABYTE];
      int bufferLength = 0;
      while ((bufferLength = inputStream.read(buffer)) > 0)
        fileOutputStream.write(buffer, 0, bufferLength);
    } catch (IOException e) {
      e.printStackTrace();
    }
    try {
      if (fileOutputStream != null) {
        fileOutputStream.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Esempio n. 15
0
 public static File getFileFromServer(String path, ProgressDialog pd) throws Exception {
   // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
   if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
     URL url = new URL(path);
     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     conn.setConnectTimeout(5000);
     // 获取到文件的大小
     pd.setMax(conn.getContentLength());
     InputStream is = conn.getInputStream();
     File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
     FileOutputStream fos = new FileOutputStream(file);
     BufferedInputStream bis = new BufferedInputStream(is);
     byte[] buffer = new byte[1024];
     int len;
     int total = 0;
     while ((len = bis.read(buffer)) != -1) {
       fos.write(buffer, 0, len);
       total += len;
       // 获取当前下载量
       pd.setProgress(total);
     }
     fos.close();
     bis.close();
     is.close();
     return file;
   } else {
     return null;
   }
 }
  @Override
  /**
   * Returns the size of the image in bytes.
   *
   * @param sourceString the image link.
   * @return the file size in bytes of the image link provided; -1 if the size isn't available or
   *     exceeds the max allowed image size.
   */
  public int getImageSize(String sourceString) {
    int length = -1;
    try {

      URL url = new URL(sourceString);
      String protocol = url.getProtocol();
      if (protocol.equals("http") || protocol.equals("https")) {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        length = connection.getContentLength();
        connection.disconnect();
      } else if (protocol.equals("ftp")) {
        FTPUtils ftp = new FTPUtils(sourceString);
        length = ftp.getSize();
        ftp.disconnect();
      }

      if (length > imgMaxSize) {
        length = -1;
      }
    } catch (Exception e) {
      logger.debug("Failed to get the length of the image in bytes", e);
    }
    return length;
  }
Esempio n. 17
0
  public static void descargar(String nombre, String idArchivo, String enlace) throws Exception {

    File folder = new File("Descargas");
    folder.mkdir();
    folder = new File("Descargas" + Con.s + nombre);
    folder.mkdir();
    String nombreArchivo = "Descargas" + Con.s + nombre + Con.s + idArchivo;

    URL url = new URL(enlace);
    HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
    httpcon.addRequestProperty("User-Agent", "Mozilla/4.76");
    httpcon.connect();
    System.out.println("Descargando:" + nombreArchivo);
    InputStream in = httpcon.getInputStream();
    OutputStream out = new FileOutputStream(nombreArchivo);
    int b = 0;
    while (b != -1) {
      b = in.read();
      if (b != -1) {
        out.write(b);
      }
    }
    out.close();
    in.close();
    System.out.println(
        "Se ha descargado " + enlace + " - " + (httpcon.getContentLength() / 1000) + " kB");
  }
Esempio n. 18
0
  public static HttpResponse getBitmap(Context context, Uri uri, Policy policy) {
    if (uri == null) {
      throw new IllegalArgumentException("uri is null");
    }
    installCacheIfNeeded(context);
    try {
      HttpURLConnection connection = (HttpURLConnection) new URL(MainActivity.URL).openConnection();
      connection.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
      connection.setReadTimeout(DEFAULT_READ_TIMEOUT);

      if (policy == Policy.Cache) {
        connection.setUseCaches(true);
      } else {
        connection.setUseCaches(false);
        connection.addRequestProperty("Cache-Control", "no-cache");
        connection.addRequestProperty("Cache-Control", "max-age=0");
      }

      int contentLen = connection.getContentLength();
      int responseCode = connection.getResponseCode();
      HttpResponse response =
          new HttpResponse(
              responseCode,
              null,
              contentLen,
              BitmapFactory.decodeStream(connection.getInputStream()));
      connection.getInputStream().close();
      return response;
    } catch (IOException e) {
      e.printStackTrace();
    }
    return null;
  }
Esempio n. 19
0
 // 下载文件
 private void download(String filePath, String destination, int threadNum) {
   try {
     // 通过下载路径获取连接
     URL url = new URL(filePath);
     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     // 设置连接的相关属性
     conn.setRequestMethod("GET");
     conn.setReadTimeout(5000);
     // 判断连接是否正确。
     if (conn.getResponseCode() == 200) {
       // 获取文件大小。
       int fileSize = conn.getContentLength();
       // 得到文件名
       String fileName = getFileName(filePath);
       // 根据文件大小及文件名,创建一个同样大小,同样文件名的文件
       File file = new File(destination + File.separator + fileName);
       RandomAccessFile raf = new RandomAccessFile(file, "rw");
       raf.setLength(fileSize);
       raf.close();
       // 将文件分成threadNum = 5份。
       int block = fileSize % threadNum == 0 ? fileSize / threadNum : fileSize / threadNum + 1;
       for (int threadId = 0; threadId < threadNum; threadId++) {
         // 传入线程编号,并开始下载。
         new DownloadThread(threadId, block, file, url).start();
       }
     }
   } catch (MalformedURLException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  public static File downLoad(String path, String savedPath, ProgressDialog pd) throws Exception {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
      URL url = new URL(path);
      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setRequestMethod("GET");
      conn.setConnectTimeout(5000);

      int code = conn.getResponseCode();
      if (code == 200) {
        pd.setMax(conn.getContentLength());

        File file = new File(savedPath);
        FileOutputStream fos = new FileOutputStream(file);
        InputStream is = conn.getInputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        int total = 0;
        while ((len = is.read(buffer)) != -1) {
          fos.write(buffer, 0, len);
          total += len;
          pd.setProgress(total);
        }
        is.close();
        fos.close();
        return file;

      } else {
        return null;
      }

    } else {
      throw new IllegalAccessException("sd card is not available now");
    }
  }
  /**
   * Discover the content length and content type for an enclosure URL
   *
   * @param rssEnclosureURL URL for enclosure
   * @return String array containing the enclosure's content length and content type
   */
  protected String[] discoverEnclosureProperties(String rssEnclosureURL) {
    String[] enclosureProperties = new String[] {"", ""};

    try {
      if (!rssEnclosureURL.toLowerCase().startsWith("http://")) {
        if (_logger.isDebugEnabled()) {
          _logger.debug("RSS enclosure URL not an HTTP-accessible resource");
        }
      } else {
        URL enclosure = new URL(rssEnclosureURL);
        HttpURLConnection httpURLConnection = (HttpURLConnection) enclosure.openConnection();
        httpURLConnection.setRequestMethod("HEAD");
        httpURLConnection.connect();

        enclosureProperties[0] = Integer.toString(httpURLConnection.getContentLength());
        enclosureProperties[1] = httpURLConnection.getContentType();

        httpURLConnection.disconnect();
      }
    } catch (Exception e) {
      if (_logger.isErrorEnabled()) {
        _logger.error("Error retrieving enclosure properties", e);
      }
    }

    return enclosureProperties;
  }
  @Override
  protected String doInBackground(String... aurl) {

    try {

      URL u = new URL(aurl[0]);
      HttpURLConnection c = (HttpURLConnection) u.openConnection();
      c.setRequestMethod("GET");
      c.setDoOutput(true);
      c.connect();

      int lenghtOfFile = c.getContentLength();

      FileOutputStream f = new FileOutputStream(new File(aurl[1]));

      InputStream in = c.getInputStream();

      byte[] buffer = new byte[1024];
      int len1 = 0;
      long total = 0;

      while ((len1 = in.read(buffer)) > 0) {
        total += len1; // total = total + len1
        publishProgress("" + (int) ((total * 100) / lenghtOfFile));
        f.write(buffer, 0, len1);
      }
      f.close();
    } catch (Exception e) {
      Log.d("Downloader", e.getMessage());
      didFailed = true;
    }

    return null;
  }
 /**
  * Opens a stream to the givne URI, also providing the MIME type & length.
  *
  * @return Never returns null.
  * @throws Throws an InvalidArgumentException for relative URIs. Relative URIs should be resolved
  *     before being passed into this function.
  * @throws Throws an IOException if the URI cannot be opened.
  * @throws Throws an IllegalStateException if called on a foreground thread and skipThreadCheck is
  *     false.
  */
 public OpenForReadResult openForRead(Uri uri, boolean skipThreadCheck) throws IOException {
   if (!skipThreadCheck) {
     assertBackgroundThread();
   }
   switch (getUriType(uri)) {
     case URI_TYPE_FILE:
       {
         FileInputStream inputStream = new FileInputStream(uri.getPath());
         String mimeType = FileHelper.getMimeTypeForExtension(uri.getPath());
         long length = inputStream.getChannel().size();
         return new OpenForReadResult(uri, inputStream, mimeType, length, null);
       }
     case URI_TYPE_ASSET:
       {
         String assetPath = uri.getPath().substring(15);
         AssetFileDescriptor assetFd = null;
         InputStream inputStream;
         long length = -1;
         try {
           assetFd = assetManager.openFd(assetPath);
           inputStream = assetFd.createInputStream();
           length = assetFd.getLength();
         } catch (FileNotFoundException e) {
           // Will occur if the file is compressed.
           inputStream = assetManager.open(assetPath);
         }
         String mimeType = FileHelper.getMimeTypeForExtension(assetPath);
         return new OpenForReadResult(uri, inputStream, mimeType, length, assetFd);
       }
     case URI_TYPE_CONTENT:
     case URI_TYPE_RESOURCE:
       {
         String mimeType = contentResolver.getType(uri);
         AssetFileDescriptor assetFd = contentResolver.openAssetFileDescriptor(uri, "r");
         InputStream inputStream = assetFd.createInputStream();
         long length = assetFd.getLength();
         return new OpenForReadResult(uri, inputStream, mimeType, length, assetFd);
       }
     case URI_TYPE_DATA:
       {
         OpenForReadResult ret = readDataUri(uri);
         if (ret == null) {
           break;
         }
         return ret;
       }
     case URI_TYPE_HTTP:
     case URI_TYPE_HTTPS:
       {
         HttpURLConnection conn = httpClient.open(new URL(uri.toString()));
         conn.setDoInput(true);
         String mimeType = conn.getHeaderField("Content-Type");
         int length = conn.getContentLength();
         InputStream inputStream = conn.getInputStream();
         return new OpenForReadResult(uri, inputStream, mimeType, length, null);
       }
   }
   throw new FileNotFoundException("URI not supported by CordovaResourceApi: " + uri);
 }
Esempio n. 24
0
  /**
   * 构建文件下载器
   *
   * @param downloadUrl 下载路径
   * @param fileSaveDir 文件保存目录
   * @param threadNum 下载线程数
   */
  public FileDownloader(Context context, String downloadUrl, File fileSaveDir, int threadNum) {
    try {
      this.context = context;
      this.downloadUrl = downloadUrl;
      fileService = new FileService(this.context);
      URL url = new URL(this.downloadUrl);
      if (!fileSaveDir.exists()) fileSaveDir.mkdirs();
      this.threads = new DownloadThread[threadNum];

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setConnectTimeout(5 * 1000);
      conn.setRequestMethod("GET");
      conn.setRequestProperty(
          "Accept",
          "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
      conn.setRequestProperty("Accept-Language", "zh-CN");
      conn.setRequestProperty("Referer", downloadUrl);
      conn.setRequestProperty("Charset", "UTF-8");
      conn.setRequestProperty(
          "User-Agent",
          "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.connect();
      if (BuildConfig.DEBUG) printResponseHeader(conn);

      if (conn.getResponseCode() == 200) {
        this.fileSize = conn.getContentLength(); // 根据响应获取文件大小
        if (this.fileSize <= 0) throw new RuntimeException("Unkown file size ");

        String filename = getFileName(conn); // 获取文件名称
        this.saveFile = new File(fileSaveDir, filename); // 构建保存文件
        Map<Integer, Integer> logdata = fileService.getData(downloadUrl); // 获取下载记录

        if (logdata.size() > 0) { // 如果存在下载记录
          for (Map.Entry<Integer, Integer> entry : logdata.entrySet())
            data.put(entry.getKey(), entry.getValue()); // 把各条线程已经下载的数据长度放入data中
        }

        if (this.data.size() == this.threads.length) { // 下面计算所有线程已经下载的数据长度
          for (int i = 0; i < this.threads.length; i++) {
            this.downloadSize += this.data.get(i + 1);
          }

          print("已经下载的长度" + this.downloadSize);
        }

        // 计算每条线程下载的数据长度
        this.block =
            (this.fileSize % this.threads.length) == 0
                ? this.fileSize / this.threads.length
                : this.fileSize / this.threads.length + 1;
      } else {
        throw new RuntimeException("server no response ");
      }
    } catch (Exception e) {
      print(e.toString());
      throw new RuntimeException("don't connection this url");
    }
  }
    @Override
    protected String doInBackground(String... sUrl) {
      InputStream input = null;
      OutputStream output = null;
      HttpURLConnection connection = null;
      try {
        URL url = new URL(sUrl[0]);
        connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        // expect HTTP 200 OK, so we don't mistakenly save error report
        // instead of the file
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
          return "Server returned HTTP "
              + connection.getResponseCode()
              + " "
              + connection.getResponseMessage();
        }

        // this will be useful to display download percentage
        // might be -1: server did not report the length
        int fileLength = connection.getContentLength();

        // download the file
        input = connection.getInputStream();
        File sdCard = Environment.getExternalStorageDirectory();

        filePathvideo = sdCard.getAbsolutePath() + "/app-release.apk";

        output = new FileOutputStream(filePathvideo);

        byte data[] = new byte[4096];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
          // allow canceling with back button
          if (isCancelled()) {
            input.close();
            return null;
          }
          total += count;
          publishProgress((int) total / 1024);
          // publishing the progress....
          if (fileLength > 0) // only if total length is known
          output.write(data, 0, count);
        }
      } catch (Exception e) {
        return e.toString();
      } finally {
        try {
          if (output != null) output.close();
          if (input != null) input.close();
        } catch (IOException ignored) {
        }

        if (connection != null) connection.disconnect();
      }
      return null;
    }
Esempio n. 26
0
    @Override
    protected File doInBackground(String... params) {
      String fileName = params[1];
      if (TextUtils.isEmpty(fileName)) {
        fileName = Uri.parse(params[0]).getLastPathSegment();
      }

      try {
        URL url = new URL(params[0]);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        double fileSize = conn.getContentLength();
        ByteArrayOutputStream os = new ByteArrayOutputStream((int) fileSize);
        conn.connect();
        InputStream is = conn.getInputStream();
        double downloaded = 0;
        byte[] buffer;
        int progress = 0;

        while (true) {
          if (fileSize - downloaded > MAX_BUFFER_SIZE) {
            buffer = new byte[MAX_BUFFER_SIZE];
          } else {
            buffer = new byte[(int) (fileSize - downloaded)];
          }

          int read = is.read(buffer);
          if (read == -1) {
            publishProgress(100);
            break;
          }

          os.write(buffer, 0, read);
          downloaded += read;

          int p = (int) ((downloaded / fileSize) * 100);
          if (progress != p) {
            progress = p;
            publishProgress(progress);
          }
        }

        File file = FileUtils.getFileStreamPath(fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(os.toByteArray());
        fos.close();

        FileUtils.chmod(file);
        return file;
      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } catch (IllegalArgumentException e) {
        e.printStackTrace();
      }
      return null;
    }
Esempio n. 27
0
 public long getFileSize() throws IOException {
   URL aURL = new URL(url);
   conn = (HttpURLConnection) aURL.openConnection();
   conn.setConnectTimeout(CONNECTION_TIME_OUT);
   conn.setReadTimeout(READING_TIME_OUT);
   long size = conn.getContentLength();
   return size;
 }
Esempio n. 28
0
    @Override
    protected Bitmap doInBackground(String... params) {

      Bitmap bmp = null;

      String url = params[0];
      URL downloadURL = null;
      HttpURLConnection conn = null;
      InputStream inputStream = null;

      try {
        downloadURL = new URL(url);
        conn = (HttpURLConnection) downloadURL.openConnection();
        int length = conn.getContentLength();
        inputStream = conn.getInputStream();
        byte[] imageData = new byte[length];
        int buffersize = (int) Math.ceil(length / (double) 100);
        int downloaded = 0;
        int read;
        while (downloaded < length) {
          if (length < buffersize) {
            read = inputStream.read(imageData, downloaded, length);
          } else if ((length - downloaded) <= buffersize) {
            read = inputStream.read(imageData, downloaded, length - downloaded);
          } else {
            read = inputStream.read(imageData, downloaded, buffersize);
          }
          downloaded += read;
          publishProgress((downloaded * 100) / length);
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);
        options.inSampleSize = calculateInSampleSize(options, 1024, 128);
        options.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeByteArray(imageData, 0, imageData.length, options);

      } catch (MalformedURLException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      } finally {

        if (conn != null) {
          conn.disconnect();
        }
        if (inputStream != null) {
          try {
            inputStream.close();
          } catch (IOException e) {
            e.printStackTrace();
          }
        }
      }

      return bmp;
    }
  public void setAndAccessURL(String urlString) {
    Log.i("tag", "akses mulai");
    //			while(isConnecting){
    try {
      if (Thread.interrupted()) listener.onCancelledConnection();

      int response = -1;

      URL url = new URL(urlString);
      conn = url.openConnection();

      if (!(conn instanceof HttpURLConnection)) throw new IOException("Not an HTTP connection");

      HttpURLConnection httpConn = (HttpURLConnection) conn;
      httpConn.setAllowUserInteraction(false);
      httpConn.setInstanceFollowRedirects(true);
      httpConn.setRequestMethod("GET");
      httpConn.setConnectTimeout(60000);
      httpConn.connect();

      int length = httpConn.getContentLength();

      response = httpConn.getResponseCode();
      if (response == HttpURLConnection.HTTP_OK) {
        is = httpConn.getInputStream();

        if (listener != null) {
          Log.i("tag", "sukses");
          listener.onReceivedResponse(is, length);
        }
      } else {
        Log.e("tag", "not ok");
        listener.onConnectionResponseNotOk();
      }

      httpConn.disconnect();
      if (is != null) {
        is.close();
        is = null;
      }

    } catch (SocketTimeoutException ex) {
      if (listener != null) {
        Log.e("error", "connection timeout");
        listener.onConnectionTimeout();
      }
    } catch (InterruptedIOException ex) {
      if (listener != null) {
        listener.onCancelledConnection();
      }
    } catch (Exception ex) {
      if (listener != null) {
        Log.e("error", "error connecting to the internet");
        listener.onConnectionError(ex);
      }
    }
    //			}
  }
Esempio n. 30
0
  /**
   * 下载网络资源
   *
   * @param pathName 资源存储路径
   * @param url 连接的URL
   * @param progress 下载进度监听
   * @return 资源文件
   */
  public File downloadFileWithProgress(String pathName, String url, Progress progress) {
    if (DEBUG) Log.d(TAG, "BetterHttp downloadFile [1] url = " + url);
    File desFile = new File(pathName); // 目标文件
    File tmpFile = new File(pathName.concat(".tmp")); // 临时文件

    if (desFile.exists()) return desFile;
    if (desFile.isDirectory()) return null;
    if (!desFile.getParentFile().exists()) desFile.getParentFile().mkdirs();

    InputStream input = null;
    OutputStream out = null;
    HttpURLConnection connection = null;

    try {
      connection = createHttpURLConnection(url, "GET");
      connection.connect();
      // 读取响应状态码
      int statusCode = connection.getResponseCode();
      if (DEBUG) Log.d(TAG, "BetterHttp downloadFile [2] StatusLine : " + statusCode);
      // 200返回码表示成功,其余的表示失败
      if (statusCode != HttpURLConnection.HTTP_OK) {
        if (DEBUG) Log.e(TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
        return null;
      }
      if (connection.getInputStream() != null) {
        tmpFile.createNewFile(); // 创建新的资源文件
        long length = connection.getContentLength(); // 网络资源字节长度
        input = new BufferedInputStream(new FlushedInputStream(connection.getInputStream()));
        out = new CountingOutputStream(new FileOutputStream(tmpFile), length, progress);

        byte buffer[] = new byte[2048];
        int readsize = 0;
        while ((readsize = input.read(buffer)) > 0) {
          out.write(buffer, 0, readsize);
        }
        input.close();
        out.flush();
        out.close();
        // 更改文件名称
        if (tmpFile.length() == length) {
          tmpFile.renameTo(desFile);
          return desFile;
        }
      }
    } catch (IOException ex) {
      if (DEBUG) {
        ex.printStackTrace();
      }
    } finally {
      if (connection != null) {
        connection.disconnect();
        connection = null;
      }
    }

    return null;
  }