List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:com.boxupp.utilities.PuppetUtilities.java
public StatusBean downloadModule(JsonNode moduleData) { Gson searchModuleData = new GsonBuilder().setDateFormat("yyyy'-'MM'-'dd HH':'mm':'ss").create(); SearchModuleBean searchModuleBean = searchModuleData.fromJson(moduleData.toString(), SearchModuleBean.class); String fileURL = CommonProperties.getInstance().getPuppetForgeDownloadAPIPath() + searchModuleBean.getCurrent_release().getFile_uri(); StatusBean statusBean = new StatusBean(); URL url = null;/* ww w .j a va 2s . c o m*/ int responseCode = 0; HttpURLConnection httpConn = null; String fileSeparator = OSProperties.getInstance().getOSFileSeparator(); String moduleDirPath = constructModuleDirectory() + fileSeparator; checkIfDirExists(new File(constructManifestsDirectory())); checkIfDirExists(new File(moduleDirPath)); try { url = new URL(fileURL); httpConn = (HttpURLConnection) url.openConnection(); responseCode = httpConn.getResponseCode(); // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String disposition = httpConn.getHeaderField("Content-Disposition"); String contentType = httpConn.getContentType(); int contentLength = httpConn.getContentLength(); if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) { fileName = disposition.substring(index + 9, disposition.length()); } } else { fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); } InputStream inputStream = httpConn.getInputStream(); String saveFilePath = moduleDirPath + fileName; FileOutputStream outputStream = new FileOutputStream(saveFilePath); int bytesRead = -1; byte[] buffer = new byte[4096]; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); extrectFile(saveFilePath, moduleDirPath, searchModuleBean.getModuleName()); File file = new File(saveFilePath); file.delete(); } else { logger.error("No file to download. Server replied HTTP code: " + responseCode); } httpConn.disconnect(); statusBean.setStatusCode(0); statusBean.setStatusMessage(" Module Downloaded successfully "); } catch (IOException e) { logger.error("Error in loading module :" + e.getMessage()); statusBean.setStatusCode(1); statusBean.setStatusMessage("Error in loading module :" + e.getMessage()); } statusBean = PuppetModuleDAOManager.getInstance().create(moduleData); return statusBean; }
From source file:com.dream.library.utils.AbFileUtil.java
/** * ????.//from w w w . j a v a 2 s .c o m * * @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("UserBean-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(); AbLog.e("?" + e.getMessage()); } return mContentLength; }
From source file:com.commsen.jwebthumb.WebThumbService.java
/** * Helper method used to actually send {@link WebThumb} request and check for common errors. * //from ww w .j a v a 2s .co m * @param webThumb the request to send * @return connection to extract the response from * @throws WebThumbException if any error occurs */ private HttpURLConnection sendWebThumb(WebThumb webThumb) throws WebThumbException { try { HttpURLConnection connection = (HttpURLConnection) new URL(WEB_THUMB_URL).openConnection(); connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setRequestMethod("POST"); SimpleXmlSerializer.generateRequest(webThumb, connection.getOutputStream()); int responseCode = connection.getResponseCode(); String contentType = getContentType(connection); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("Request sent! Got response: " + responseCode + " " + connection.getResponseMessage()); LOGGER.fine("Response content type: " + contentType); LOGGER.fine("Response content encoding: " + connection.getContentEncoding()); LOGGER.fine("Response content length: " + connection.getContentLength()); } if (responseCode == HttpURLConnection.HTTP_OK) { if (CONTENT_TYPE_TEXT_PLAIN.equals(contentType)) { throw new WebThumbException( "Server side error: " + IOUtils.toString(connection.getInputStream())); } if (!CONTENT_TYPE_TEXT_XML.equals(contentType)) { throw new WebThumbException("Unknown content type in response: " + contentType); } return connection; } else { throw new WebThumbException("Server side error: " + connection.getResponseCode() + ") " + connection.getResponseMessage()); } } catch (MalformedURLException e) { throw new WebThumbException("failed to send request", e); } catch (IOException e) { throw new WebThumbException("failed to send request", e); } }
From source file:com.inter.trade.view.slideplayview.util.AbFileUtil.java
/** * ????./*from w w w . j a va 2 s . c o m*/ * * @param Url * @return int ? */ public static int getContentLengthFormUrl(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(); if (D) Log.d(TAG, "?" + e.getMessage()); } return mContentLength; }
From source file:com.portfolio.data.attachment.FileServlet.java
void InitAnswer(HttpURLConnection connection, HttpServletResponse response, String referer) throws MalformedURLException, IOException { String ref = null;//from ww w . ja va2s. co m if (referer != null) { int first = referer.indexOf('/', 7); int last = referer.lastIndexOf('/'); ref = referer.substring(first, last); } response.setContentType(connection.getContentType()); response.setStatus(connection.getResponseCode()); response.setContentLength(connection.getContentLength()); /// Transfer headers Map<String, List<String>> headers = connection.getHeaderFields(); int size = headers.size(); for (int i = 1; i < size; ++i) { String key = connection.getHeaderFieldKey(i); String value = connection.getHeaderField(i); // response.setHeader(key, value); response.addHeader(key, value); } /// Deal with correct path with set cookie List<String> setValues = headers.get("Set-Cookie"); if (setValues != null) { String setVal = setValues.get(0); int pathPlace = setVal.indexOf("Path="); if (pathPlace > 0) { setVal = setVal.substring(0, pathPlace + 5); // Some assumption, may break setVal = setVal + ref; response.setHeader("Set-Cookie", setVal); } } }
From source file:com.github.hexocraftapi.updater.updater.Downloader.java
/** * Download the file and save it to the updater folder. *///from w ww .j ava 2s.c om private boolean downloadFile() { BufferedInputStream in = null; FileOutputStream fout = null; try { // Init connection HttpURLConnection connection = (HttpURLConnection) initConnection(this.update.getDownloadUrl()); // always check HTTP response code first int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_MOVED_TEMP || responseCode == HttpURLConnection.HTTP_MOVED_PERM || responseCode == HttpURLConnection.HTTP_SEE_OTHER) { String newUrl = connection.getHeaderField("Location"); connection = (HttpURLConnection) initConnection(new URL(newUrl)); responseCode = connection.getResponseCode(); } // always check HTTP response code first if (responseCode == HttpURLConnection.HTTP_OK) { String fileName = ""; String fileURL = this.update.getDownloadUrl().toString(); String disposition = connection.getHeaderField("Content-Disposition"); String contentType = connection.getContentType(); int fileLength = connection.getContentLength(); // extracts file name from header field if (disposition != null) { int index = disposition.indexOf("filename="); if (index > 0) fileName = disposition.substring(index + 10, disposition.length() - 1); } // extracts file name from URL else fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length()); // opens input stream from the HTTP connection in = new BufferedInputStream(connection.getInputStream()); // opens an output stream to save into file fout = new FileOutputStream(new File(this.updateFolder, fileName)); log(Level.INFO, "About to download a new update: " + this.update.getVersion().toString()); final byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead; while ((bytesRead = in.read(buffer, 0, BUFFER_SIZE)) != -1) fout.write(buffer, 0, bytesRead); log(Level.INFO, "File downloaded: " + fileName); } } catch (Exception ex) { log(Level.WARNING, "The auto-updater tried to download a new update, but was unsuccessful."); return false; } finally { try { if (in != null) in.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } try { if (fout != null) fout.close(); } catch (final IOException ex) { log(Level.SEVERE, null); return false; } return true; } }
From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java
private void downloadExternalFile(String url, File localDestination, ProgressListener listener) throws IOException { URL downloadUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("Content-Type", "application/octet-stream"); connection.setRequestMethod("GET"); connection.setDoInput(true);/*from w w w . j a va2s.c o m*/ try { if (connection.getResponseCode() != 200) { throw new NonSuccessfulResponseCodeException("Bad response: " + connection.getResponseCode()); } OutputStream output = new FileOutputStream(localDestination); InputStream input = connection.getInputStream(); byte[] buffer = new byte[4096]; int contentLength = connection.getContentLength(); int read, totalRead = 0; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); totalRead += read; if (listener != null) { listener.onAttachmentProgress(contentLength, totalRead); } } output.close(); Log.w(TAG, "Downloaded: " + url + " to: " + localDestination.getAbsolutePath()); } catch (IOException ioe) { throw new PushNetworkException(ioe); } finally { connection.disconnect(); } }
From source file:org.eclipse.rdf4j.http.server.ProtocolTest.java
@Test public void testUpdateResponse_HEAD() throws Exception { String query = "INSERT DATA { <foo:foo> <foo:bar> \"foo\". } "; String location = Protocol.getStatementsLocation(TestServer.REPOSITORY_URL); location += "?update=" + URLEncoder.encode(query, "UTF-8"); URL url = new URL(location); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.connect();/*from www .j av a 2 s . com*/ try { int responseCode = conn.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { String contentType = conn.getHeaderField("Content-Type"); assertNotNull(contentType); // snip off optional charset declaration int charPos = contentType.indexOf(";"); if (charPos > -1) { contentType = contentType.substring(0, charPos); } assertEquals(0, conn.getContentLength()); } else { String response = "location " + location + " responded: " + conn.getResponseMessage() + " (" + responseCode + ")"; fail(response); throw new RuntimeException(response); } } finally { conn.disconnect(); } }
From source file:uk.ac.ucl.excites.sapelli.collector.util.AsyncDownloader.java
private boolean download(String downloadUrl) { if (downloadUrl == null || downloadUrl.isEmpty()) { failure = new Exception("No URL given!"); return false; }/*from w w w. jav a2 s . com*/ //Log.d(getClass().getSimpleName(), "Download URL: " + downloadUrl); if (DeviceControl.isOnline(context)) { InputStream input = null; OutputStream output = null; try { URL url = new URL(downloadUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setInstanceFollowRedirects(false); // we handle redirects manually below (otherwise HTTP->HTTPS redirects don't work): conn.connect(); // Detect & follow redirects: int status = conn.getResponseCode(); //Log.d(getClass().getSimpleName(), "Response Code: " + status); if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM || status == HttpURLConnection.HTTP_SEE_OTHER) { // follow redirect url from "location" header field String newUrl = conn.getHeaderField("Location"); //Log.d(getClass().getSimpleName(), "Redirect to URL : " + newUrl); return download(newUrl); } // Getting file length final int fileLength = conn.getContentLength(); publishProgress(fileLength < 0 ? // when fileLength = -1 this means the server hasn't specified the file length -1 : // progressDialog will open and be set to indeterminate mode 0); // progressDialog will open and be set to 0 // Input stream to read file - with 8k buffer input = new BufferedInputStream(url.openStream(), 8192); // Output stream to write file output = new BufferedOutputStream(new FileOutputStream(downloadedFile)); byte data[] = new byte[1024]; int total = 0; int percentage = 0; int bytesRead; while ((bytesRead = input.read(data)) != -1) { // Complete % completion: if (fileLength > 0) // don't divide by 0 and only update progress if we know the fileLength (i.e. != -1) { int newPercentage = (int) ((total += bytesRead) / ((float) fileLength) * 100f); if (newPercentage != percentage) publishProgress(percentage = newPercentage); } // Write data to file... output.write(data, 0, bytesRead); } // Flush output: output.flush(); } catch (Exception e) { failure = e; return false; } finally { // Close streams: StreamHelpers.SilentClose(input); StreamHelpers.SilentClose(output); } //Log.d(getClass().getSimpleName(), "Download done"); return true; } else { failure = new Exception("The device is not online."); return false; } }
From source file:com.docdoku.cli.helpers.FileHelper.java
public String downloadFile(File pLocalFile, String pURL) throws IOException, LoginException, NoSuchAlgorithmException { ConsoleProgressMonitorInputStream in = null; OutputStream out = null;/*from www.ja va 2s. c o m*/ HttpURLConnection conn = null; try { //Hack for NTLM proxy //perform a head method to negociate the NTLM proxy authentication URL url = new URL(pURL); System.out.println("Downloading file: " + pLocalFile.getName() + " from " + url.getHost()); performHeadHTTPMethod(url); out = new BufferedOutputStream(new FileOutputStream(pLocalFile), BUFFER_CAPACITY); conn = (HttpURLConnection) url.openConnection(); conn.setUseCaches(false); conn.setAllowUserInteraction(true); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestMethod("GET"); byte[] encoded = Base64.encodeBase64((login + ":" + password).getBytes("ISO-8859-1")); conn.setRequestProperty("Authorization", "Basic " + new String(encoded, "US-ASCII")); conn.connect(); manageHTTPCode(conn); MessageDigest md = MessageDigest.getInstance("MD5"); in = new ConsoleProgressMonitorInputStream(conn.getContentLength(), new DigestInputStream(new BufferedInputStream(conn.getInputStream(), BUFFER_CAPACITY), md)); byte[] data = new byte[CHUNK_SIZE]; int length; while ((length = in.read(data)) != -1) { out.write(data, 0, length); } out.flush(); byte[] digest = md.digest(); return Base64.encodeBase64String(digest); } finally { if (out != null) out.close(); if (in != null) in.close(); if (conn != null) conn.disconnect(); } }