List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:com.zzl.zl_app.cache.Utility.java
public static boolean loadFile(String loadpath, String fileName, String savePath, Context context, String broadcastAction) { FileOutputStream fos = null; // ? FileInputStream fis = null; // ? InputStream is = null; // ? HttpURLConnection httpConnection = null; int readLength = 0; // ?? int file_length = 0; URL url = null;/* w ww. jav a 2s . com*/ try { url = new URL(loadpath); httpConnection = (HttpURLConnection) url.openConnection(); httpConnection.setConnectTimeout(10000); httpConnection.setRequestMethod("GET"); is = httpConnection.getInputStream(); FileTools.creatDir(savePath); String filePath = savePath + fileName; FileTools.deleteFile(filePath); FileTools.creatFile(filePath); File download_file = new File(filePath); fos = new FileOutputStream(download_file, true); // ?? fis = new FileInputStream(download_file); // ?? int total_read = fis.available(); // ??0 file_length = httpConnection.getContentLength(); // ? if (is == null) { // ? Tools.log("Voice", "donload failed..."); return false; } byte buf[] = new byte[3072]; // readLength = 0; // Tools.log("Voice", "download start..."); Intent startIntent = new Intent(); Bundle b = new Bundle(); if (broadcastAction != null) { // ????? b.putInt("fileSize", file_length); b.putInt("progress", 0); startIntent.putExtras(b); startIntent.setAction(broadcastAction); context.sendBroadcast(startIntent); } // ????? while (readLength != -1) { if ((readLength = is.read(buf)) > 0) { fos.write(buf, 0, readLength); total_read += readLength; // } if (broadcastAction != null) { b.putInt("fileSize", file_length); b.putInt("progress", total_read); startIntent.putExtras(b); startIntent.setAction(broadcastAction); context.sendBroadcast(startIntent); } if (total_read == file_length) { // ? Tools.log("Voice", "download complete..."); // ?????? if (broadcastAction != null) { Intent completeIntent = new Intent(); b.putBoolean("isFinish", true); completeIntent.putExtras(b); completeIntent.setAction(broadcastAction); context.sendBroadcast(completeIntent); } } // Thread.sleep(10); // ?10 } } catch (Exception e) { if (broadcastAction != null) { Intent errorIntent = new Intent(); errorIntent.setAction(broadcastAction); context.sendBroadcast(errorIntent); e.printStackTrace(); } } finally { try { if (fos != null) { fos.close(); } if (fis != null) { is.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } return true; }
From source file:com.apache.ivy.BasicURLHandler.java
public URLInfo getURLInfo(URL url, int timeout) { // Install the IvyAuthenticator if ("http".equals(url.getProtocol()) || "https".equals(url.getProtocol())) { IvyAuthenticator.install();//from ww w . j av a2 s . c o m } URLConnection con = null; try { url = normalizeToURL(url); con = url.openConnection(); con.setRequestProperty("User-Agent", "Apache Ivy/1.0");//+ Ivy.getIvyVersion()); if (con instanceof HttpURLConnection) { HttpURLConnection httpCon = (HttpURLConnection) con; if (getRequestMethod() == URLHandler.REQUEST_METHOD_HEAD) { httpCon.setRequestMethod("HEAD"); } if (checkStatusCode(url, httpCon)) { String bodyCharset = getCharSetFromContentType(con.getContentType()); return new URLInfo(true, httpCon.getContentLength(), con.getLastModified(), bodyCharset); } } else { int contentLength = con.getContentLength(); if (contentLength <= 0) { return UNAVAILABLE; } else { // TODO: not HTTP... maybe we *don't* want to default to ISO-8559-1 here? String bodyCharset = getCharSetFromContentType(con.getContentType()); return new URLInfo(true, contentLength, con.getLastModified(), bodyCharset); } } } catch (UnknownHostException e) { // Message.warn("Host " + e.getMessage() + " not found. url=" + url); // Message.info("You probably access the destination server through " // + "a proxy server that is not well configured."); } catch (IOException e) { //Message.error("Server access error at url " + url, e); } finally { disconnect(con); } return UNAVAILABLE; }
From source file:eu.codeplumbers.cosi.services.CosiFileDownloadService.java
@Override protected void onHandleIntent(Intent intent) { // Do the task here Log.i(CosiFileDownloadService.class.getName(), "Cosi Service running"); // Release the wake lock provided by the WakefulBroadcastReceiver. WakefulBroadcastReceiver.completeWakefulIntent(intent); Device device = Device.registeredDevice(); // cozy register device url fileUrl = device.getUrl() + "/ds-api/data/"; // concatenate username and password with colon for authentication final String credentials = device.getLogin() + ":" + device.getPassword(); authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP); showNotification();//from w ww . ja v a 2 s. c o m if (isNetworkAvailable()) { try { ArrayList<String> fileStrings = intent.getStringArrayListExtra("fileToDownload"); for (int i = 0; i < fileStrings.size(); i++) { File file = File.load(File.class, Long.valueOf(fileStrings.get(i))); String binaryRemoteId = file.getRemoteId(); if (!binaryRemoteId.isEmpty()) { mBuilder.setProgress(100, 0, false); mBuilder.setContentText("Downloading file: " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); URL urlO = null; try { urlO = new URL(fileUrl + binaryRemoteId + "/binaries/file"); HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoInput(true); conn.setRequestMethod("GET"); conn.connect(); int lenghtOfFile = conn.getContentLength(); // read the response int status = conn.getResponseCode(); if (status >= HttpURLConnection.HTTP_BAD_REQUEST) { EventBus.getDefault() .post(new FileSyncEvent(SERVICE_ERROR, conn.getResponseMessage())); stopSelf(); } else { int count = 0; InputStream in = new BufferedInputStream(conn.getInputStream(), 8192); java.io.File newFile = file.getLocalPath(); if (!newFile.exists()) { newFile.createNewFile(); } // Output stream to write file OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory() + java.io.File.separator + Constants.APP_DIRECTORY + java.io.File.separator + "files" + file.getPath() + "/" + file.getName()); byte data[] = new byte[1024]; long total = 0; while ((count = in.read(data)) != -1) { total += count; mBuilder.setProgress(lenghtOfFile, (int) total, false); mBuilder.setContentText("Downloading file: " + file.getName()); mNotifyManager.notify(notification_id, mBuilder.build()); // writing data to file output.write(data, 0, count); } // flushing output output.flush(); // closing streams output.close(); in.close(); file.setDownloaded(true); file.save(); } } catch (MalformedURLException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (ProtocolException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } catch (IOException e) { EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); stopSelf(); } } } mNotifyManager.cancel(notification_id); EventBus.getDefault().post(new FileSyncEvent(REFRESH, "Sync OK")); } catch (Exception e) { e.printStackTrace(); mSyncRunning = false; EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, e.getLocalizedMessage())); } } else { mSyncRunning = false; EventBus.getDefault().post(new FileSyncEvent(SERVICE_ERROR, "No Internet connection")); mBuilder.setContentText("Sync failed because no Internet connection was available"); mNotifyManager.notify(notification_id, mBuilder.build()); } }
From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java
/** * Reads the response from the URL connection. * * @param conn//from w w w. j a v a 2s .co m * URL from which to read response * @param res * {@link SampleResult} to read response into * @return response content * @exception IOException * if an I/O exception occurs */ protected byte[] readResponse(HttpURLConnection conn, SampleResult res) throws IOException { BufferedInputStream in; final int contentLength = conn.getContentLength(); if ((contentLength == 0) && OBEY_CONTENT_LENGTH) { log.info("Content-Length: 0, not reading http-body"); res.setResponseHeaders(getResponseHeaders(conn)); res.latencyEnd(); return NULL_BA; } // works OK even if ContentEncoding is null boolean gzipped = HTTPConstants.ENCODING_GZIP.equals(conn.getContentEncoding()); InputStream instream = null; try { instream = new CountingInputStream(conn.getInputStream()); if (gzipped) { in = new BufferedInputStream(new GZIPInputStream(instream)); } else { in = new BufferedInputStream(instream); } } catch (IOException e) { if (!(e.getCause() instanceof FileNotFoundException)) { log.error("readResponse: " + e.toString()); Throwable cause = e.getCause(); if (cause != null) { log.error("Cause: " + cause); if (cause instanceof Error) { throw (Error) cause; } } } // Normal InputStream is not available InputStream errorStream = conn.getErrorStream(); if (errorStream == null) { log.info("Error Response Code: " + conn.getResponseCode() + ", Server sent no Errorpage"); res.setResponseHeaders(getResponseHeaders(conn)); res.latencyEnd(); return NULL_BA; } log.info("Error Response Code: " + conn.getResponseCode()); if (gzipped) { in = new BufferedInputStream(new GZIPInputStream(errorStream)); } else { in = new BufferedInputStream(errorStream); } } catch (Exception e) { log.error("readResponse: " + e.toString()); Throwable cause = e.getCause(); if (cause != null) { log.error("Cause: " + cause); if (cause instanceof Error) { throw (Error) cause; } } in = new BufferedInputStream(conn.getErrorStream()); } // N.B. this closes 'in' byte[] responseData = readResponse(res, in, contentLength); if (instream != null) { res.setBodySize(((CountingInputStream) instream).getCount()); instream.close(); } return responseData; }
From source file:com.joyent.manta.client.MantaClientSigningIT.java
@Test public final void testCanCreateSignedHEADUriFromPath() throws IOException { if (config.isClientEncryptionEnabled()) { throw new SkipException("Signed URLs are not decrypted by the client"); }//from w ww .j ava2 s . c o m final String name = UUID.randomUUID().toString(); final String path = testPathPrefix + name; mantaClient.put(path, TEST_DATA); // This will throw an error if the newly inserted object isn't present mantaClient.head(path); Instant expires = Instant.now().plus(1, ChronoUnit.HOURS); URI uri = mantaClient.getAsSignedURI(path, "HEAD", expires); HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection(); try { connection.setReadTimeout(3000); connection.setRequestMethod("HEAD"); connection.connect(); Map<String, List<String>> headers = connection.getHeaderFields(); if (connection.getResponseCode() != 200) { Assert.fail(IOUtils.toString(connection.getErrorStream(), Charset.defaultCharset())); } Assert.assertNotNull(headers); Assert.assertEquals(TEST_DATA.length(), connection.getContentLength()); } finally { connection.disconnect(); } }
From source file:net.ytbolg.mcxa.ForgeCheck.java
void downloadFile(String remoteFilePath, String localFilePath) { URL urlfile = null;//from w w w . j a v a 2 s . c o m HttpURLConnection httpUrl = null; BufferedInputStream bis = null; BufferedOutputStream bos = null; File f = new File(localFilePath); File xxxx = new File(f.getParent()); xxxx.mkdirs(); // f.mkdirs(); try { urlfile = new URL(remoteFilePath); httpUrl = (HttpURLConnection) urlfile.openConnection(); httpUrl.connect(); j.setMaximum(httpUrl.getContentLength()); j.setValue(0); bis = new BufferedInputStream(httpUrl.getInputStream()); bos = new BufferedOutputStream(new FileOutputStream(f)); int len = 2048; byte[] b = new byte[len]; int i = 0; while ((len = bis.read(b)) != -1) { i = i + len; j.setValue(i); l.setText(i / 1024 + "/" + (httpUrl.getContentLength() / 1024) + "KB"); bos.write(b, 0, len); } bos.flush(); bis.close(); httpUrl.disconnect(); } catch (Exception e) { e.printStackTrace(); } finally { try { bis.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:org.digitalcampus.oppia.task.DownloadCourseTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];//from www . j av a 2 s .c om Course dm = (Course) payload.getData().get(0); DownloadProgress dp = new DownloadProgress(); try { HTTPConnectionUtils client = new HTTPConnectionUtils(ctx); String url = client.createUrlWithCredentials(dm.getDownloadUrl()); Log.d(TAG, "Downloading:" + url); URL u = new URL(url); HttpURLConnection c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); c.setConnectTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection), ctx.getString(R.string.prefServerTimeoutConnection)))); c.setReadTimeout(Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response), ctx.getString(R.string.prefServerTimeoutResponse)))); int fileLength = c.getContentLength(); String localFileName = dm.getShortname() + "-" + String.format("%.0f", dm.getVersionId()) + ".zip"; dp.setMessage(localFileName); dp.setProgress(0); publishProgress(dp); Log.d(TAG, "saving to: " + localFileName); FileOutputStream f = new FileOutputStream(new File(MobileLearning.DOWNLOAD_PATH, localFileName)); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; long total = 0; int progress = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; progress = (int) (total * 100) / fileLength; if (progress > 0) { dp.setProgress(progress); publishProgress(dp); } f.write(buffer, 0, len1); } f.close(); dp.setProgress(100); publishProgress(dp); dp.setMessage(ctx.getString(R.string.download_complete)); publishProgress(dp); payload.setResult(true); } catch (ClientProtocolException cpe) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(cpe); } else { cpe.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (SocketTimeoutException ste) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(ste); } else { ste.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (IOException ioe) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(ioe); } else { ioe.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } return payload; }
From source file:com.hmsoft.libcommon.gopro.GoProController.java
private byte[] execCommand(String controller, String command, String param) { String urlStr = "http://" + mCameraAddress + "/" + controller + "/" + command; if (mPassword != null) { urlStr += "?t=" + mPassword; }//from ww w .ja v a 2s .c o m if (param != null) { urlStr += "&p=" + param; } HttpURLConnection urlConnection = getHttpURLConnection(urlStr); if (urlConnection == null) return null; try { InputStream in = urlConnection.getInputStream(); int cl = urlConnection.getContentLength(); byte[] buffer = new byte[cl]; in.read(buffer); if (Logger.DEBUG || logCommandAndResponse) logCommandAndResponse(urlStr, buffer); return buffer; } catch (FileNotFoundException e) { Logger.warning(TAG, "Not found: " + removePassword(urlStr)); return RESPONSE_NOT_FOUND; } catch (IOException e) { Logger.warning(TAG, "Can't connect to camera: " + removePassword(urlStr), e); return null; } finally { urlConnection.disconnect(); } }
From source file:sample.multithreading.ImageDownloaderThread.java
public void run() { mThread = Thread.currentThread(); android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); Bitmap bmReturn = null;/*w w w.j av a 2s .c o m*/ try { if (Thread.interrupted()) return; byte[] imageBuf = sCache.get(mLocation); if (null == imageBuf) { mHandler.sendEmptyMessage(DOWNLOAD_STARTED); InputStream is = null; try { HttpURLConnection httpConn = (HttpURLConnection) mLocation.openConnection(); httpConn.setRequestProperty("User-Agent", NetworkDownloadService.USER_AGENT); if (Thread.interrupted()) return; is = httpConn.getInputStream(); if (Thread.interrupted()) return; int contentLength = httpConn.getContentLength(); /* * We take advantage of the content length if it is returned * to preallocate our buffer. If it is not returned, we end * up thrashing memory a bit more. */ if (-1 == contentLength) { byte[] buf = new byte[READ_SIZE]; int bufferLeft = buf.length; int offset = 0; int result = 0; outer: do { while (bufferLeft > 0) { result = is.read(buf, offset, bufferLeft); if (result < 0) { // we're done break outer; } offset += result; bufferLeft -= result; if (Thread.interrupted()) return; } // resize bufferLeft = READ_SIZE; int newSize = buf.length + READ_SIZE; byte[] newBuf = new byte[newSize]; System.arraycopy(buf, 0, newBuf, 0, buf.length); buf = newBuf; } while (true); imageBuf = new byte[offset]; System.arraycopy(buf, 0, imageBuf, 0, offset); } else { imageBuf = new byte[contentLength]; int length = contentLength; int offset = 0; while (length > 0) { int result = is.read(imageBuf, offset, length); if (result < 0) { throw new EOFException(); } offset += result; length -= result; if (Thread.interrupted()) return; } } if (Thread.interrupted()) return; } catch (IOException e) { return; } finally { if (null != is) { try { is.close(); } catch (Exception e) { } } } } mHandler.sendEmptyMessage(DECODE_QUEUED); try { sCoreAvailable.acquire(); mHandler.sendEmptyMessage(DECODE_STARTED); BitmapFactory.Options bfo = new BitmapFactory.Options(); int targetWidth = mTargetWidth; int targetHeight = mTargetHeight; if (Thread.interrupted()) return; bfo.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(imageBuf, 0, imageBuf.length, bfo); int hScale = bfo.outHeight / targetHeight; int wScale = bfo.outWidth / targetWidth; int sampleSize = Math.max(hScale, wScale); if (sampleSize > 1) { bfo.inSampleSize = sampleSize; } if (Thread.interrupted()) return; bfo.inJustDecodeBounds = false; // oom handling in decode stage for (int i = 0; i < NUMBER_OF_DECODE_TRIES; i++) { try { bmReturn = BitmapFactory.decodeByteArray(imageBuf, 0, imageBuf.length, bfo); // break out of OOM loop break; } catch (Throwable e) { Log.e(LOG_TAG, "Out of memory in decode stage. Throttling."); java.lang.System.gc(); if (Thread.interrupted()) return; try { Thread.sleep(0xfa); } catch (java.lang.InterruptedException ix) { } } } if (mCache) { sCache.put(mLocation, imageBuf); } } catch (java.lang.InterruptedException x) { x.printStackTrace(); } finally { sCoreAvailable.release(); } } finally { mThread = null; if (null == bmReturn) { mHandler.sendEmptyMessage(DOWNLOAD_FAILED); } else { Message completeMessage = mHandler.obtainMessage(TASK_COMPLETE, bmReturn); completeMessage.sendToTarget(); } // clear interrupt flag Thread.interrupted(); } }
From source file:com.chiorichan.updater.Download.java
@Override public void run() { ReadableByteChannel rbc = null; FileOutputStream fos = null;/*from ww w.j av a 2 s .c o m*/ try { HttpURLConnection conn = NetworkFunc.openHttpConnection(url); int response = conn.getResponseCode(); int responseFamily = response / 100; if (responseFamily == 3) throw new DownloadException( "The server issued a redirect response which the Updater failed to follow."); else if (responseFamily != 2) throw new DownloadException("The server issued a " + response + " response code."); InputStream in = getConnectionInputStream(conn); size = conn.getContentLength(); outFile = new File(outPath); outFile.delete(); rbc = Channels.newChannel(in); fos = new FileOutputStream(outFile); stateChanged(); Thread progress = new MonitorThread(Thread.currentThread(), rbc); progress.start(); fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE); in.close(); rbc.close(); progress.interrupt(); if (size > 0) { if (size == outFile.length()) result = Result.SUCCESS; } else result = Result.SUCCESS; stateDone(); } catch (DownloadDeniedException e) { exception = e; result = Result.PERMISSION_DENIED; } catch (DownloadException e) { exception = e; result = Result.FAILURE; } catch (Exception e) { exception = e; e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(rbc); } if (exception != null) AutoUpdater.getLogger().severe("Download Resulted in an Exception", exception); }