Java Code Examples for java.net.httpurlconnection#getContentLength()

The following examples show how to use java.net.httpurlconnection#getContentLength() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GoProController.java    From android-wear-gopro-remote with Apache License 2.0 6 votes vote down vote up
public CameraInfo getCameraInfo() {
    HttpURLConnection connection = getMediaConnection("videos/MISC/", "version.txt", null);
    if(connection == null) return null;
    try {
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            int cl = connection.getContentLength();
            StringBuilder builder = cl > 0 ? new StringBuilder(cl) : new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
            return new CameraInfo(builder.toString());
        } finally {
            connection.disconnect();
        }
    } catch (IOException e){
        Logger.warning(TAG, "Error getting version.txt", e);
    }
    return null;
}
 
Example 2
Source File: FileUtils.java    From DevUtils with Apache License 2.0 6 votes vote down vote up
/**
 * 获取文件大小 - 网络资源
 * @param httpUri 文件网络链接
 * @return 文件大小
 */
public static long getFileLengthNetwork(final String httpUri) {
    if (StringUtils.isSpace(httpUri)) return 0L;
    // 判断是否网络资源
    boolean isHttpRes = httpUri.toLowerCase().startsWith("http:") || httpUri.toLowerCase().startsWith("https:");
    if (isHttpRes) {
        try {
            HttpURLConnection conn = (HttpURLConnection) new URL(httpUri).openConnection();
            conn.setRequestProperty("Accept-Encoding", "identity");
            conn.connect();
            if (conn.getResponseCode() == 200) {
                return conn.getContentLength();
            }
            return 0L;
        } catch (Exception e) {
            JCLogUtils.eTag(TAG, e, "getFileLengthNetwork");
        }
    }
    return 0L;
}
 
Example 3
Source File: YandexTranslate.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * This method reads from a stream based on the passed connection
 * @param connection the connection to read from
 * @return the contents of the stream
 * @throws IOException if it cannot read from the http connection
 */
private static String getResponseContent(HttpURLConnection connection) throws IOException {
  // Use the content encoding to convert bytes to characters.
  String encoding = connection.getContentEncoding();
  if (encoding == null) {
    encoding = "UTF-8";
  }
  InputStreamReader reader = new InputStreamReader(connection.getInputStream(), encoding);
  try {
    int contentLength = connection.getContentLength();
    StringBuilder sb = (contentLength != -1)
        ? new StringBuilder(contentLength)
        : new StringBuilder();
    char[] buf = new char[1024];
    int read;
    while ((read = reader.read(buf)) != -1) {
      sb.append(buf, 0, read);
    }
    return sb.toString();
  } finally {
    reader.close();
  }
}
 
Example 4
Source File: WebHdfsFileSystem.java    From hadoop with Apache License 2.0 6 votes vote down vote up
static Map<?, ?> jsonParse(final HttpURLConnection c, final boolean useErrorStream
    ) throws IOException {
  if (c.getContentLength() == 0) {
    return null;
  }
  final InputStream in = useErrorStream? c.getErrorStream(): c.getInputStream();
  if (in == null) {
    throw new IOException("The " + (useErrorStream? "error": "input") + " stream is null.");
  }
  try {
    final String contentType = c.getContentType();
    if (contentType != null) {
      final MediaType parsed = MediaType.valueOf(contentType);
      if (!MediaType.APPLICATION_JSON_TYPE.isCompatible(parsed)) {
        throw new IOException("Content-Type \"" + contentType
            + "\" is incompatible with \"" + MediaType.APPLICATION_JSON
            + "\" (parsed=\"" + parsed + "\")");
      }
    }
    ObjectMapper mapper = new ObjectMapper();
    return mapper.reader(Map.class).readValue(in);
  } finally {
    in.close();
  }
}
 
Example 5
Source File: BaseImageDownloader.java    From Android-Application-ZJB with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves {@link InputStream} of image by URI (image is located in the network).
 *
 * @param imageUri Image URI
 * @param extra    Auxiliary object which was passed to {@link DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link InputStream} of image
 * @throws IOException if some I/O error occurs during network request or if no InputStream could be created for
 *                     URL.
 */
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    HttpURLConnection conn = createConnection(imageUri, extra);

    int redirectCount = 0;
    while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) {
        conn = createConnection(conn.getHeaderField("Location"), extra);
        redirectCount++;
    }

    InputStream imageStream;
    try {
        imageStream = conn.getInputStream();
    } catch (IOException e) {
        // Read all data to allow reuse connection (http://bit.ly/1ad35PY)
        IoUtils.readAndCloseStream(conn.getErrorStream());
        throw e;
    }
    if (!shouldBeProcessed(conn)) {
        IoUtils.closeSilently(imageStream);
        throw new IOException("Image request failed with response code " + conn.getResponseCode());
    }

    return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength());
}
 
Example 6
Source File: ExprUrlSizeBytes.java    From skUtilities with GNU General Public License v3.0 6 votes vote down vote up
@Override
@Nullable
protected Number[] get(Event e) {
  try {
    HttpURLConnection c = (HttpURLConnection) new URL(url.getSingle(e)).openConnection();
    c.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");
    Number n = c.getContentLength();
    c.disconnect();
    if (n.intValue() == -1) {
      skUtilities.prSysE("Url: '" + url.getSingle(e) + "' returned no information about the url's size!", getClass().getSimpleName());
    } else {
      return new Number[]{n};
    }
  } catch (Exception x) {
    skUtilities.prSysE("Error Reading from: '" + url.getSingle(e) + "' Is the site down?", getClass().getSimpleName(), x);
  }
  return null;
}
 
Example 7
Source File: InstagramDownloader.java    From Instagram-Downloader with Apache License 2.0 6 votes vote down vote up
private void download(String url, String targetDirectory){
    String[] tempName = url.split("/");
    String filename = tempName[tempName.length-1].split("[?]")[0];

    try(InputStream inputStream = URI.create(url).toURL().openStream()){
        HttpURLConnection conn = (HttpURLConnection)URI.create(url).toURL().openConnection();

        Path targetPath = new File(targetDirectory + File.separator + filename).toPath();
        Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);

        int BYTES_PER_KB = 1024;
        double fileSize = ((double)conn.getContentLength() / BYTES_PER_KB);

        System.out.println("Media file downloaded successfully.");
        System.out.println(String.format("Media Location: %s", targetPath));
        System.out.println(String.format("Media Name: %s", filename));
        System.out.println(String.format("Media Size: %.2f kb", fileSize));
        System.out.println(String.format("Media Type: %s", Helpers.mediaType(filename)));

    } catch (IOException e){
        e.printStackTrace();
    }
}
 
Example 8
Source File: MyImageDownloader.java    From repay-android with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieves {@link java.io.InputStream} of image by URI (image is located in the network).
 *
 * @param imageUri Image URI
 * @param extra    Auxiliary object which was passed to {@link com.nostra13.universalimageloader.core.DisplayImageOptions.Builder#extraForDownloader(Object)
 *                 DisplayImageOptions.extraForDownloader(Object)}; can be null
 * @return {@link java.io.InputStream} of image
 * @throws java.io.IOException if some I/O error occurs during network request or if no InputStream could be created for
 *                     URL.
 */
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
	HttpURLConnection conn = createConnection(imageUri, extra);

	int redirectCount = 0;
	while (conn.getResponseCode() / 100 == 3 && redirectCount < MAX_REDIRECT_COUNT) {
		conn = createConnection(conn.getHeaderField("Location"), extra);
		redirectCount++;
	}

	InputStream imageStream;
	try {
		imageStream = conn.getInputStream();
	} catch (IOException e) {
		// Read all data to allow reuse connection (http://bit.ly/1ad35PY)
		IoUtils.readAndCloseStream(conn.getErrorStream());
		throw e;
	}
	return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength());
}
 
Example 9
Source File: Downloader.java    From Game with GNU General Public License v3.0 6 votes vote down vote up
private void download(File file) {
	try {
		String fileURL = file.toString().replace(Constants.CONF_DIR + File.separator, Constants.CACHE_URL).replace(File.separator, "/");
		String description = getDescription(file);
		AppFrame.get().setDownloadProgress(description, 0);
		HttpURLConnection connection = (HttpURLConnection) new URL(fileURL).openConnection();
		try (BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
			 FileOutputStream fileOutputStream = new FileOutputStream(file)) {
			int filesize = connection.getContentLength();
			byte[] dataBuffer = new byte[1024];
			int bytesRead;
			int totalRead = 0;
			while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) {
				totalRead += bytesRead;
				fileOutputStream.write(dataBuffer, 0, bytesRead);
				AppFrame.get().setDownloadProgress(description, (float) (totalRead * 100 / filesize));
			}
			AppFrame.get().setDownloadProgress(description, 100.0f);
		} catch (IOException e) {
			e.printStackTrace();
		}
		connection.disconnect();
	} catch (Exception a) {
		a.printStackTrace();
	}
}
 
Example 10
Source File: GetFileInfoTask.java    From AndroidDownloader with Apache License 2.0 6 votes vote down vote up
private void parseHttpResponse(HttpURLConnection httpConnection, boolean isAcceptRanges)
        throws DownloadException {

    final long length;
    String contentLength = httpConnection.getHeaderField("Content-Length");
    if (TextUtils.isEmpty(contentLength) || contentLength.equals("0") || contentLength
            .equals("-1")) {
        length = httpConnection.getContentLength();
    } else {
        length = Long.parseLong(contentLength);
    }

    if (length <= 0) {
        throw new DownloadException(DownloadException.EXCEPTION_FILE_SIZE_ZERO, "length <= 0");
    }

    checkIfPause();

    onGetFileInfoListener.onSuccess(length, isAcceptRanges);
}
 
Example 11
Source File: BaseImageDownloader.java    From MiBandDecompiled with Apache License 2.0 6 votes vote down vote up
protected InputStream getStreamFromNetwork(String s, Object obj)
{
    HttpURLConnection httpurlconnection = createConnection(s, obj);
    for (int i = 0; httpurlconnection.getResponseCode() / 100 == 3 && i < 5; i++)
    {
        httpurlconnection = createConnection(httpurlconnection.getHeaderField("Location"), obj);
    }

    InputStream inputstream;
    try
    {
        inputstream = httpurlconnection.getInputStream();
    }
    catch (IOException ioexception)
    {
        IoUtils.readAndCloseStream(httpurlconnection.getErrorStream());
        throw ioexception;
    }
    return new ContentLengthInputStream(new BufferedInputStream(inputstream, 32768), httpurlconnection.getContentLength());
}
 
Example 12
Source File: BaseImageDownloader.java    From letv with Apache License 2.0 5 votes vote down vote up
protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws IOException {
    HttpURLConnection conn = createConnection(imageUri, extra);
    int redirectCount = 0;
    while (conn.getResponseCode() / 100 == 3 && redirectCount < 5) {
        conn = createConnection(conn.getHeaderField(HttpRequest.HEADER_LOCATION), extra);
        redirectCount++;
    }
    try {
        return new ContentLengthInputStream(new BufferedInputStream(conn.getInputStream(), 32768), conn.getContentLength());
    } catch (IOException e) {
        IoUtils.readAndCloseStream(conn.getErrorStream());
        throw e;
    }
}
 
Example 13
Source File: HttpClientUtils.java    From NetworkDisk_Storage with GNU General Public License v2.0 5 votes vote down vote up
public static String httpPostWithJSON(String postUrl, String json) {
        try {
            URL url = new URL(postUrl);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(json);
            out.flush();
            out.close();
            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            InputStream is = connection.getInputStream();
            String result = IoConvertUtils.stream2String(is);
            return result;
//            if (length != -1) {
//                byte[] data = new byte[length];
//                byte[] temp = new byte[512];
//                int readLen = 0;
//                int destPos = 0;
//                while ((readLen = is.read(temp)) > 0) {
//                    System.arraycopy(temp, 0, data, destPos, readLen);
//                    destPos += readLen;
//                }
//                String result = new String(data, "UTF-8"); // utf-8编码
//                // System.out.println(result);
//                return result;
//            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息
    }
 
Example 14
Source File: Downloader.java    From MMDownloader with Apache License 2.0 5 votes vote down vote up
/**
 * 내부적으로 이용되는 download 메서드<br>
 * String 형식의 이미지 주소를 받아서 다운로드<br>
 * <i>추후 HttpComponent로 변경 예정</i>
 *
 * @return 다운로드한 이미지의 byte size
 * @throws Exception
 */
private int download() throws Exception {
	HttpURLConnection conn = (HttpURLConnection) new URL(imgURL).openConnection();
	conn.setRequestMethod("GET");
	conn.setConnectTimeout(MAX_WAIT_TIME); // init 연결 타임아웃
	conn.setConnectTimeout(MAX_WAIT_TIME << 1); // data read 타임아웃
	conn.setRequestProperty("charset", "utf-8");
	conn.setRequestProperty("User-Agent", UserAgent.getUserAgent());
	//conn.setRequestProperty("Accept-Encoding", "gzip");
	conn.setRequestProperty("Host", host);
	conn.setRequestProperty("Referer", referer);

	int imageSize = conn.getContentLength(); // byte size
	InputStream inputStream = conn.getInputStream(); //속도저하의 원인

	String savePath = String.format("%s%03d%s", path, pageNum, getExt(imgURL, ".jpg"));

	BufferedInputStream bis = new BufferedInputStream(inputStream, BUF_SIZE);
	BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(savePath), BUF_SIZE);

	IOUtils.copyLarge(bis, bos);

	bos.close();
	bis.close();

	return imageSize;
}
 
Example 15
Source File: FileDownloader.java    From EasyFileDownloader with Apache License 2.0 4 votes vote down vote up
private void prepareDownload() {
    this.targetStatus = DOWNLOAD_STATUS_START;
    this.threads = new DownloadThread[config.getThreadNum()];
    if (!this.config.getSaveDir().exists()) {
        if (!this.config.getSaveDir().mkdirs()) {
            LogUtils.d(TAG, "mkdirs download directory failed.");
            return;
        }
    }

    HttpURLConnection urlConn = openConnection(config.getDownloadUrl());
    try {
        if (urlConn.getResponseCode() == 200) {
            this.fileSize = urlConn.getContentLength();
            if (this.fileSize <= 0) {
                throw new RuntimeException("unKnow file size");
            }
            onDownloadTotalSize(this.fileSize);
        } else {
            throw new RuntimeException("server no response.");
        }
    } catch (IOException e) {
        e.printStackTrace();
        LogUtils.d(TAG, "open HttpURLConnection failed.");
        Toast.makeText(mContext, "open url failed.", Toast.LENGTH_SHORT).show();
        onDownloadFailed();
        return;
    }

    String fileName = this.config.getFileName();
    if (TextUtils.isEmpty(fileName)) {
        fileName = getFileName(urlConn, config.getDownloadUrl());
    }
    this.saveFile = new File(this.config.getSaveDir(), fileName);
    LogUtils.d(TAG, "saveFile.path = " + this.saveFile.getPath());
    this.data = new ArrayList<>(downloadDBHelper.query(config.getDownloadUrl()));
    if (this.data.size() == this.threads.length) {
        for (ThreadData threadData : this.data) {
            this.downloadSize += threadData.getDownloadLength();
        }
        LogUtils.d(TAG, "history download size = " + this.downloadSize);
    } else {
        this.data.clear();
        for (int i = 0; i < this.threads.length; i++) {
            this.data.add(new ThreadData(i, this.fileSize));//Initialize each thread has downloaded data length is zero
        }
        this.downloadSize = 0;
        this.downloadDBHelper.save(this.config.getDownloadUrl(), this.data);//first save
    }
    //Calculating the maximum length of data download each thread
    this.block = (this.fileSize % this.threads.length) == 0 ?
            this.fileSize / this.threads.length :
            this.fileSize / this.threads.length + 1;
    executeDownload();
}
 
Example 16
Source File: DownloadPostFragment.java    From Instagram-Profile-Downloader with MIT License 4 votes vote down vote up
protected List<String> doInBackground(String... args) {
    String fileName = GlobalConstant.SAVED_FILE_NAME + "-" + System.currentTimeMillis() + ".mp4";

    File file = new File(Environment.getExternalStorageDirectory().toString() + File.separator + GlobalConstant.SAVED_FILE_NAME);
    if (!file.exists()) file.mkdirs();


    Downloads downloads = new Downloads();
    downloads.setUser_id("");
    downloads.setPath(file.getAbsolutePath() + "/" + fileName);
    downloads.setUsername("");
    downloads.setType(1);
    downloads.setFilename(fileName);
    DataObjectRepositry.dataObjectRepositry.addDownloadedData(downloads);

    newVid = new File(file, fileName);
    if (!newVid.exists())
        try {
            newVid.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.connect();
        int lenghtOfFile = connection.getContentLength();
        FileOutputStream out = new FileOutputStream(newVid);
        InputStream is = connection.getInputStream();
        byte[] buffer = new byte[1024];
        long total = 0;
        while (true) {
            int len1 = is.read(buffer);
            total += (long) len1;
            publishProgress(new Integer[]{Integer.valueOf((int) ((100 * total) / ((long) lenghtOfFile)))});
            if (len1 == -1) {
                break;
            }
            out.write(buffer, 0, len1);
        }
        out.close();
        is.close();
    } catch (Exception e2) {
        e2.printStackTrace();
    }
    return null;
}
 
Example 17
Source File: MainActivity.java    From Android-Basics-Codes with Artistic License 2.0 4 votes vote down vote up
private void requestNet() {
	// (1). �����ͷ�������Դ�ļ�һ����С�Ŀ��ļ�
	try {
		// 1. ��ʼ��Url
		URL url = new URL(path);
		// 2. ͨ��Url��ȡHttp����
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		// 3. �����������������ʽ
		conn.setRequestMethod("GET");
		// 4. ��ȡ������ 200:�ɹ� 3xxx���� 4xxx�ͻ��˴��� 500����������
		int code = conn.getResponseCode();
		// 5. �õ��ӷ������˷��ص���Դ�ļ��Ĵ�С
		int fileLength = conn.getContentLength();
		if (code == 200) {
			System.out.println("��������Դ�ļ��Ĵ�С��" + fileLength);
			RandomAccessFile raf = new RandomAccessFile(getFileName(), "rw");
			// ��Ҫ�����ļ��Ĵ�С
			raf.setLength(fileLength);
			raf.close();
		}

		// (2).��������߳�����
		// ÿ������Ĵ�С
		int blockSize = fileLength / threadCount;

		for (int threadId = 0; threadId < threadCount; threadId++) {
			int startIndex = threadId * blockSize;
			int endIndex = (threadId + 1) * blockSize;
			// ���һ���߳�
			if (threadId == threadCount - 1) {
				// �����ļ�������λ��
				endIndex = fileLength - 1;
			}
			// ��ʼ�߳�
			new DownLoadThread(startIndex, endIndex, threadId).start();
		}

	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 18
Source File: UpdateService.java    From Fishing with GNU General Public License v3.0 4 votes vote down vote up
@Override
protected Boolean doInBackground(String... params) {
	JUtils.Log("StartDownLoadTask");
	path = params[1];
	name = params[2];
	boolean finish = false;
	try{
		URL url = new URL(params[0]);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		if(conn.getResponseCode() == 200) {
			File f = new File(params[1]);
			if (!f.isDirectory()) {
				f.mkdirs();
			}
			InputStream is = conn.getInputStream();
			int length = conn.getContentLength();
			File file = new File(path+name);
			FileOutputStream fos = new FileOutputStream(file);
			int count = 0;
			byte buf[] = new byte[1024];
			int progress = 0;
			int progress_pre = 0;
			do {
				int numread = is.read(buf);
				count += numread;
				progress = (int) (((float) count / length) * 100);
				if(progress != progress_pre){
					JUtils.Log("progress"+progress);
					publishProgress(progress);
					progress_pre = progress;
				}
				
				if (numread <= 0) {				
					break;
				}
				fos.write(buf, 0, numread);
			} while (!cancelUpdate);
			fos.flush();
			fos.close();
			is.close();
			finish = true;
		}
	} catch (Exception e) {
		JUtils.Log(e.getLocalizedMessage());
		finish = false;
	}				
	return finish;
}
 
Example 19
Source File: DownloadThread.java    From UnityOBBDownloader with Apache License 2.0 4 votes vote down vote up
/**
 * Read headers from the HTTP response and store them into local state.
 */
private void readResponseHeaders(State state, InnerState innerState, HttpURLConnection response)
        throws StopRequest {
    String value = response.getHeaderField("Content-Disposition");
    if (value != null) {
        innerState.mHeaderContentDisposition = value;
    }
    value = response.getHeaderField("Content-Location");
    if (value != null) {
        innerState.mHeaderContentLocation = value;
    }
    value = response.getHeaderField("ETag");
    if (value != null) {
        innerState.mHeaderETag = value;
    }
    String headerTransferEncoding = null;
    value = response.getHeaderField("Transfer-Encoding");
    if (value != null) {
        headerTransferEncoding = value;
    }
    String headerContentType = null;
    value = response.getHeaderField("Content-Type");
    if (value != null) {
        headerContentType = value;
        if (!headerContentType.equals("application/vnd.android.obb")) {
            throw new StopRequest(DownloaderService.STATUS_FILE_DELIVERED_INCORRECTLY,
                    "file delivered with incorrect Mime type");
        }
    }

    if (headerTransferEncoding == null) {
        long contentLength = response.getContentLength();
        if (value != null) {
            // this is always set from Market
            if (contentLength != -1 && contentLength != mInfo.mTotalBytes) {
                // we're most likely on a bad wifi connection -- we should
                // probably
                // also look at the mime type --- but the size mismatch is
                // enough
                // to tell us that something is wrong here
                Log.e(Constants.TAG, "Incorrect file size delivered.");
            } else {
                innerState.mHeaderContentLength = Long.toString(contentLength);
            }
        }
    } else {
        // Ignore content-length with transfer-encoding - 2616 4.4 3
        if (Constants.LOGVV) {
            Log.v(Constants.TAG,
                    "ignoring content-length because of xfer-encoding");
        }
    }
    if (Constants.LOGVV) {
        Log.v(Constants.TAG, "Content-Disposition: " +
                innerState.mHeaderContentDisposition);
        Log.v(Constants.TAG, "Content-Length: " + innerState.mHeaderContentLength);
        Log.v(Constants.TAG, "Content-Location: " + innerState.mHeaderContentLocation);
        Log.v(Constants.TAG, "ETag: " + innerState.mHeaderETag);
        Log.v(Constants.TAG, "Transfer-Encoding: " + headerTransferEncoding);
    }

    boolean noSizeInfo = innerState.mHeaderContentLength == null
            && (headerTransferEncoding == null
            || !headerTransferEncoding.equalsIgnoreCase("chunked"));
    if (noSizeInfo) {
        throw new StopRequest(DownloaderService.STATUS_HTTP_DATA_ERROR,
                "can't know size of download, giving up");
    }
}
 
Example 20
Source File: SystemInfo.java    From MMDownloader with Apache License 2.0 4 votes vote down vote up
/**
 * <p>최신버전 다운로드 메서드.
 * <p>최신버전 확인 메서드 내부에서 불러지는 용도로만 사용하게 제한.
 * <p>사용자의 OS 값에 따라서 윈도우 / 그 이외(맥, 리눅스) 버전을 다운로드
 * @param in 키보드 입력용 버퍼리더 객체
 */
private static void downloadLatestVersion(final BufferedReader in){
	try{
		final int MB = 1048576;
		final int BUF_SIZE = MB * 10;
		
		String select, fileName = null, fileURL = null;
		boolean isCorrectlySelected = false;
		
		while(!isCorrectlySelected){ //다운로드 받거나(y) 취소(n)를 제대로 선택할 때 까지 반복.
			System.out.printf("최신 버전(%s)을 다운받으시겠습니까? (Y/n): ", LATEST_VERSION);
			select = in.readLine();
			
			if(select.equalsIgnoreCase("y")){
				isCorrectlySelected = true;
				makeDir(); //Marumaru폴더 생성
				
				/* OS가 윈도우면, 파일 이름 = MMdownloader_0.5.0.0_Windows.zip */
				if(OS_NAME.contains("Windows")){
					fileName = LATEST_WINDOWS.substring(LATEST_WINDOWS.lastIndexOf("/")+1);
					fileURL = LATEST_WINDOWS;
				}
				/* OS가 윈도우 이외면 파일 이름 = MMdownloader_0.5.0.0_Mac,Linux.zip */
				else{
					fileName = LATEST_OTHERS.substring(LATEST_OTHERS.lastIndexOf("/")+1);
					fileURL = LATEST_OTHERS;
				}
				
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(DEFAULT_PATH+fileSeparator+fileName), BUF_SIZE);
				HttpURLConnection conn = (HttpURLConnection)new URL(fileURL).openConnection();
				conn.setConnectTimeout(30000); // 타임아웃 30초 
				conn.setReadTimeout(60000); // 타임아웃 1분
				
				BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), BUF_SIZE);
				
				final double MB_SIZE = (double) conn.getContentLength() / MB;	// 전체 파일 사이즈의 MB 값
				int readByte = 0;	// 읽은 바이트 값
				int accum = 0;		// 누적 바이트 길이
				int count = 0;		// MB 를 넘기 전 까지 읽어들인 바이트 길이
				
				System.out.println("다운로드중 ...");
				
				while((readByte = bis.read()) != -1){
					bos.write(readByte);
					
					/* MB 별로 다운로드 진행 상황을 출력함 */
					if(++count >= MB) {
						accum += count;
						count = 0;
						System.out.printf("%,3.2f MB / %,3.2f MB 완료!\n", (double) accum / MB, MB_SIZE);
					}
				}
				bos.close();
				bis.close();
				
				System.out.printf("%,3.2f MB / %,3.2f MB 완료!\n", (double) (accum + count) / MB, MB_SIZE);
				System.out.println("완료! (위치: "+DEFAULT_PATH+fileSeparator+fileName+")");
			}
			else if(select.equalsIgnoreCase("n")){
				isCorrectlySelected = true;
				System.out.println("업데이트가 취소되었습니다.");
			}
		}
	}
	catch(Exception e){
		ErrorHandling.saveErrLog("최신버전 다운로드 에러", "", e);
	}
}