List of usage examples for java.net HttpURLConnection getContentLength
public int getContentLength()
From source file:filters.BaseFilter.java
public void filter(URL url, OutputStream output, FilterOptions options) throws IOException, EmptyExtensionException, NotSupportedFormatException, FileTooBigException { String format = SupportedFormats.supportFormat(url.toString()); if (StringUtils.isBlank(format)) { throw new NotSupportedFormatException(); }//w ww . ja v a2 s.c om // Calculate size HttpURLConnection openConnection = (HttpURLConnection) url.openConnection(); int contentLength = openConnection.getContentLength(); if (contentLength > FILE_SIZE_LIMIT) { throw new FileTooBigException(); } openConnection.disconnect(); BufferedImage read = ImageIO.read(url); doFilter(read, output, options, format); }
From source file:Main.java
int contentLength(URL url) { HttpURLConnection connection; int contentLength = -1; try {// w ww . j a va 2 s . c om connection = (HttpURLConnection) url.openConnection(); contentLength = connection.getContentLength(); } catch (Exception e) { } return contentLength; }
From source file:org.jclouds.http.internal.JavaUrlHttpCommandExecutorService.java
/** * Only disconnect if there is no content, as disconnecting will throw away unconsumed content. *//* ww w . j av a 2 s . c o m*/ @Override protected void cleanup(HttpURLConnection connection) { if (connection != null && connection.getContentLength() == 0) connection.disconnect(); }
From source file:common.net.volley.toolbox.HurlStack.java
/** * Initializes an {@link org.apache.http.HttpEntity} from the given {@link java.net.HttpURLConnection}. * @param connection/*from ww w. ja v a 2 s . c o m*/ * @return an HttpEntity populated with data from <code>connection</code>. */ private static HttpEntity entityFromConnection(HttpURLConnection connection) throws IOException { BasicHttpEntity entity = new BasicHttpEntity(); ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream rawStream = null; try { rawStream = connection.getInputStream(); rawStream = stethoManager.interpretResponseStream(rawStream); InputStream decompressedStream = applyDecompressionIfApplicable(connection, rawStream); if (decompressedStream != null) { copy(decompressedStream, out, new byte[1024]); } entity.setContent(new ByteArrayInputStream(out.toByteArray())); } catch (IOException ioe) { rawStream = connection.getErrorStream(); entity.setContent(rawStream); } finally { // if(rawStream != null) { // rawStream.close(); // } } entity.setContentLength(connection.getContentLength()); entity.setContentEncoding(connection.getContentEncoding()); entity.setContentType(connection.getContentType()); return entity; }
From source file:myapp.Download.java
@Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { URL url = new URL("http://download.geofabrik.de/europe/great-britain/england/hertfordshire-latest.osm.bz2"); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); int contentLength = uc.getContentLength(); InputStream raw = uc.getInputStream(); //BZip2CompressorInputStream unzippedstream = new BZip2CompressorInputStream(raw); XmlWriter xmlWriter;/* w ww .j a v a 2s . c om*/ TagFilter rejectWayTagFilter, rejectRelationTagFilter, nodeTagFilter; DBWriter dbwriter; xmlReader = new XMLNetworkReader(raw, true, CompressionMethod.BZip2); xmlWriter = new XmlWriter(new File("-"), CompressionMethod.None); dbwriter = new DBWriter(); Map emptymap = new HashMap<String, Set<String>>(); Set emptyset = new HashSet<String>(); rejectWayTagFilter = new TagFilter("reject-ways", emptyset, emptymap); rejectRelationTagFilter = new TagFilter("reject-relations", emptyset, emptymap); Map tagKVs = new HashMap<String, Set<String>>(); // Set tagset = new HashSet<String>(); Set valueSet = new HashSet<String>(); // tagset.add("shop"); valueSet.add("tree"); tagKVs.put("natural", valueSet); nodeTagFilter = new TagFilter("accept-nodes", emptyset, tagKVs); xmlReader.setSink(rejectWayTagFilter); rejectWayTagFilter.setSink(rejectRelationTagFilter); rejectRelationTagFilter.setSink(nodeTagFilter); nodeTagFilter.setSink(dbwriter); xmlReader.run(); // rejectWayTagFilter.process(); // rejectRelationTagFilter.process(); // nodeTagFilter.process(); // InputStream in = new BufferedInputStream(raw); // byte[] data = new byte[contentLength]; // int bytesRead = 0; // int offset = 0; // while (offset < contentLength) { // bytesRead = in.read(data, offset, data.length - offset); // if (bytesRead == -1) { // break; // } // offset += bytesRead; // } // if (offset != contentLength) { // throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes"); // } // add file to cloud storage // List<Acl> acls = new ArrayList(); // acls.add(Acl.of(Acl.User.ofAllUsers(), Acl.Role.READER)); // // the inputstream is closed by default, so we don't need to close it here // Blob blob = storage.create(BlobInfo.builder(BUCKET_NAME, "jhjg").acl(acls).build(), // unzippedstream) // new SinkSourceManager( // "tag filter", // new TagFilter(getDefaultStringArgument(taskConfig, ""), keys, keyValues), // taskConfig.getPipeArgs() // ); // Map<String, Set<String>> tags = new HashMap<String, Set<String>>; // Set setA = new HashSet(); // String element = "supermarket"; // setA.add(element); // tags.put("shop",setA) // new TagFilter("accept-nodes", null, tags) resp.setContentType("text/plain"); resp.getWriter().println("{ \"download\": true }"); // in.close(); }
From source file:org.apache.hadoop.fs.azure.SelfThrottlingIntercept.java
public void responseReceived(ResponseReceivedEvent event) { RequestResult result = event.getRequestResult(); Date startDate = result.getStartDate(); Date stopDate = result.getStopDate(); long elapsed = stopDate.getTime() - startDate.getTime(); synchronized (this) { this.lastE2Elatency = elapsed; }/*from w ww.j a v a2s. c om*/ if (LOG.isDebugEnabled()) { int statusCode = result.getStatusCode(); String etag = result.getEtag(); HttpURLConnection urlConnection = (HttpURLConnection) event.getConnectionObject(); int contentLength = urlConnection.getContentLength(); String requestMethod = urlConnection.getRequestMethod(); long threadId = Thread.currentThread().getId(); LOG.debug(String.format( "SelfThrottlingIntercept:: ResponseReceived: threadId=%d, Status=%d, Elapsed(ms)=%d, ETAG=%s, contentLength=%d, requestMethod=%s", threadId, statusCode, elapsed, etag, contentLength, requestMethod)); } }
From source file:org.droidparts.http.RESTClient.java
public Pair<Integer, BufferedInputStream> getInputStream(String uri) throws HTTPException { L.d("InputStream on " + uri); int contentLength = -1; ConsumingInputStream cis = null;//www .j a v a 2 s .c o m if (useHttpURLConnection()) { HttpURLConnectionWrapper wrapper = getModern(); HttpURLConnection conn = wrapper.getConnectedHttpURLConnection(uri, GET); contentLength = conn.getContentLength(); cis = new ConsumingInputStream(HttpURLConnectionWrapper.getUnpackedInputStream(conn), conn); } else { DefaultHttpClientWrapper wrapper = getLegacy(); HttpGet req = new HttpGet(uri); HttpResponse resp = wrapper.getResponse(req); HttpEntity entity = resp.getEntity(); // 2G limit contentLength = (int) entity.getContentLength(); cis = new ConsumingInputStream(DefaultHttpClientWrapper.getUnpackedInputStream(entity), entity); } return new Pair<Integer, BufferedInputStream>(contentLength, cis); }
From source file:fr.ironcraft.assets.FileDownloader.java
private int tryGetFileSize(URL url) { HttpURLConnection conn = null; try {//from w w w. java 2 s . c o m conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("HEAD"); conn.getInputStream(); return conn.getContentLength(); } catch (IOException e) { return -1; } finally { conn.disconnect(); } }
From source file:org.sipfoundry.sipxivr.rest.RestfulRequest.java
/** * Convenience method to send a request to a URL * //from ww w. j av a2 s . com * @param method an HTTP method, PUT, DELETE, POST, GET, etc. * where no body is provided. * Any response (assumed to be text) is in m_content; * @throws Exception */ boolean send(String method, String value) throws Exception { HttpURLConnection urlConn = getConnection(value); boolean result = request(method, urlConn); if (urlConn.getContentLength() > 0) { m_contentType = urlConn.getContentType(); BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; m_content = ""; for (line = br.readLine(); line != null;) { m_content.concat(line); m_content.concat("\n"); } } urlConn.disconnect(); return result; }
From source file:org.droidparts.http.worker.HttpURLConnectionWorker.java
public Pair<Integer, BufferedInputStream> getInputStream(String uri) throws HTTPException { HttpURLConnection conn = getConnection(uri, GET); HttpURLConnectionWorker.connectAndGetResponseCodeOrThrow(conn); int contentLength = conn.getContentLength(); HTTPInputStream is = HTTPInputStream.getInstance(conn, false); return new Pair<Integer, BufferedInputStream>(contentLength, is); }