/** * Loads the drawing. By convention this method is invoked on a worker thread. * * @param progress A ProgressIndicator to inform the user about the progress of the operation. * @return The Drawing that was loaded. */ protected Drawing loadDrawing(ProgressIndicator progress) throws IOException { Drawing drawing = createDrawing(); if (getParameter("datafile") != null) { URL url = new URL(getDocumentBase(), getParameter("datafile")); URLConnection uc = url.openConnection(); // Disable caching. This ensures that we always request the // newest version of the drawing from the server. // (Note: The server still needs to set the proper HTTP caching // properties to prevent proxies from caching the drawing). if (uc instanceof HttpURLConnection) { ((HttpURLConnection) uc).setUseCaches(false); } // Read the data into a buffer int contentLength = uc.getContentLength(); InputStream in = uc.getInputStream(); try { if (contentLength != -1) { in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); progress.setIndeterminate(false); } BufferedInputStream bin = new BufferedInputStream(in); bin.mark(512); // Read the data using all supported input formats // until we succeed IOException formatException = null; for (InputFormat format : drawing.getInputFormats()) { try { bin.reset(); } catch (IOException e) { uc = url.openConnection(); in = uc.getInputStream(); in = new BoundedRangeInputStream(in); ((BoundedRangeInputStream) in).setMaximum(contentLength + 1); progress.setProgressModel((BoundedRangeModel) in); bin = new BufferedInputStream(in); bin.mark(512); } try { bin.reset(); format.read(bin, drawing, true); formatException = null; break; } catch (IOException e) { formatException = e; } } if (formatException != null) { throw formatException; } } finally { in.close(); } } return drawing; }
static { Attributes m = null; final URL loc = Prop.LOCATION; if (loc != null) { final String jar = loc.getFile(); try { final ClassLoader cl = JarManifest.class.getClassLoader(); final Enumeration<URL> list = cl.getResources("META-INF/MANIFEST.MF"); while (list.hasMoreElements()) { final URL url = list.nextElement(); if (!url.getFile().contains(jar)) continue; final InputStream in = url.openStream(); try { m = new Manifest(in).getMainAttributes(); break; } finally { in.close(); } } } catch (final IOException ex) { Util.errln(ex); } } MAP = m; }
public void run() { try { Thread.sleep(10); byte[] buf = getBuf(); URL url = new URL("http://127.0.0.1:" + port + "/test"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); con.setRequestProperty( "Content-Type", "Multipart/Related; type=\"application/xop+xml\"; boundary=\"----=_Part_0_6251267.1128549570165\"; start-info=\"text/xml\""); OutputStream out = con.getOutputStream(); out.write(buf); out.close(); InputStream in = con.getInputStream(); byte[] newBuf = readFully(in); in.close(); if (buf.length != newBuf.length) { System.out.println("Doesn't match"); error = true; } synchronized (lock) { ++received; if ((received % 1000) == 0) { System.out.println("Received=" + received); } } } catch (Exception e) { // e.printStackTrace(); System.out.print("."); error = true; } }
@Override public InputStream getInputStream() throws IOException, UnsupportedFileOperationException { VsphereConnHandler connHandler = null; try { connHandler = getConnHandler(); ManagedObjectReference fileManager = getFileManager(connHandler); FileTransferInformation fileDlInfo = connHandler .getClient() .getVimPort() .initiateFileTransferFromGuest(fileManager, vm, credentials, getPathInVm()); String fileDlUrl = fileDlInfo.getUrl().replace("*", connHandler.getClient().getServer()); // http://stackoverflow.com/questions/921262/how-to-download-and-save-a-file-from-internet-using-java URL website = new URL(fileDlUrl); return website.openStream(); } catch (InvalidPropertyFaultMsg e) { translateandLogException(e); } catch (RuntimeFaultFaultMsg e) { translateandLogException(e); } catch (FileFaultFaultMsg e) { translateandLogException(e); } catch (GuestOperationsFaultFaultMsg e) { translateandLogException(e); } catch (InvalidStateFaultMsg e) { translateandLogException(e); } catch (TaskInProgressFaultMsg e) { translateandLogException(e); } finally { releaseConnHandler(connHandler); } return null; }
public static String visitWeb(String urlStr) { URL url = null; HttpURLConnection httpConn = null; InputStream in = null; try { url = new URL(urlStr); httpConn = (HttpURLConnection) url.openConnection(); HttpURLConnection.setFollowRedirects(true); httpConn.setRequestMethod("GET"); httpConn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 6.0;Windows 2000)"); in = httpConn.getInputStream(); return convertStreamToString(in); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); httpConn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } } return null; }
public Set<String> listResources(String subdir) { try { Set<String> result = new HashSet<String>(); if (resourceURL != null) { String protocol = resourceURL.getProtocol(); if (protocol.equals("jar")) { String resPath = resourceURL.getPath(); int pling = resPath.lastIndexOf("!"); URL jarURL = new URL(resPath.substring(0, pling)); String resDirInJar = resPath.substring(pling + 2); String prefix = resDirInJar + subdir + "/"; // System.out.printf("BaseMod.listResources: looking for names starting with %s\n", // prefix); JarFile jar = new JarFile(new File(jarURL.toURI())); Enumeration<JarEntry> entries = jar.entries(); while (entries.hasMoreElements()) { String name = entries.nextElement().getName(); if (name.startsWith(prefix) && !name.endsWith("/") && !name.contains("/.")) { // System.out.printf("BaseMod.listResources: name = %s\n", name); result.add(name.substring(prefix.length())); } } } else throw new RuntimeException("Resource URL protocol " + protocol + " not supported"); } return result; } catch (Exception e) { throw new RuntimeException(e); } }
private boolean handshake() throws Exception { URL homePage = new URL("http://mangaonweb.com/viewer.do?ctsn=" + ctsn); HttpURLConnection urlConn = (HttpURLConnection) homePage.openConnection(); urlConn.connect(); if (urlConn.getResponseCode() == HttpURLConnection.HTTP_NOT_FOUND) return (false); // save the cookie String headerName = null; for (int i = 1; (headerName = urlConn.getHeaderFieldKey(i)) != null; i++) { if (headerName.equals("Set-Cookie")) { cookies = urlConn.getHeaderField(i); } } // save cdn and crcod String page = "", line; BufferedReader stream = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8")); while ((line = stream.readLine()) != null) page += line; cdn = param(page, "cdn"); crcod = param(page, "crcod"); return (true); }
public static void setAZTracker(URL tracker_url, boolean az_tracker) { String key = tracker_url.getHost() + ":" + tracker_url.getPort(); synchronized (az_trackers) { boolean changed = false; if (az_trackers.get(key) == null) { if (az_tracker) { az_trackers.put(key, new Long(SystemTime.getCurrentTime())); changed = true; } } else { if (!az_tracker) { if (az_trackers.remove(key) != null) { changed = true; } } } if (changed) { COConfigurationManager.setParameter("Tracker Client AZ Instances", az_trackers); } } }
private boolean processURL(URL url, String baseDir, StatusWindow status) throws IOException { if (processedLinks.contains(url)) { return false; } else { processedLinks.add(url); } URLConnection connection = url.openConnection(); InputStream in = new BufferedInputStream(connection.getInputStream()); ArrayList list = processPage(in, baseDir, url); if ((status != null) && (list.size() > 0)) { status.setMaximum(list.size()); } for (int i = 0; i < list.size(); i++) { if (status != null) { status.setMessage(Utils.trimFileName(list.get(i).toString(), 40), i); } if ((!((String) list.get(i)).startsWith("RUN")) && (!((String) list.get(i)).startsWith("SAVE")) && (!((String) list.get(i)).startsWith("LOAD"))) { processURL( new URL(url.getProtocol(), url.getHost(), url.getPort(), (String) list.get(i)), baseDir, status); } } in.close(); return true; }
public static void main(String[] args) { try { if (args.length == 1) { URL url = new URL(args[0]); System.out.println("Content-Type: " + url.openConnection().getContentType()); // Vector links = extractLinks(url); // for (int n = 0; n < links.size(); n++) { // System.out.println((String) links.elementAt(n)); // } Set links = extractLinksWithText(url).entrySet(); Iterator it = links.iterator(); while (it.hasNext()) { Map.Entry en = (Map.Entry) it.next(); String strLink = (String) en.getKey(); String strText = (String) en.getValue(); System.out.println(strLink + " \"" + strText + "\" "); } return; } else if (args.length == 2) { writeURLtoFile(new URL(args[0]), args[1]); return; } } catch (Exception e) { System.err.println("An error occured: "); e.printStackTrace(); // System.err.println(e.toString()); } System.err.println("Usage: java SaveURL <url> [<file>]"); System.err.println("Saves a URL to a file."); System.err.println("If no file is given, extracts hyperlinks on url to console."); }
public boolean shutdown(int port, boolean ssl) { try { String protocol = "http" + (ssl ? "s" : ""); URL url = new URL(protocol, "127.0.0.1", port, "shutdown"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("servicemanager", "shutdown"); conn.connect(); StringBuffer sb = new StringBuffer(); BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); int n; char[] cbuf = new char[1024]; while ((n = br.read(cbuf, 0, cbuf.length)) != -1) sb.append(cbuf, 0, n); br.close(); String message = sb.toString().replace("<br>", "\n"); if (message.contains("Goodbye")) { cp.appendln("Shutting down the server:"); String[] lines = message.split("\n"); for (String line : lines) { cp.append("..."); cp.appendln(line); } return true; } } catch (Exception ex) { } cp.appendln("Unable to shutdown CTP"); return false; }
/** * Parse a repository document. * * @param url * @throws IOException * @throws XmlPullParserException * @throws Exception */ void parseDocument(URL url) throws IOException, XmlPullParserException, Exception { if (!visited.contains(url)) { visited.add(url); try { System.out.println("Visiting: " + url); InputStream in = null; if (url.getPath().endsWith(".zip")) { ZipInputStream zin = new ZipInputStream(url.openStream()); ZipEntry entry = zin.getNextEntry(); while (entry != null) { if (entry.getName().equals("repository.xml")) { in = zin; break; } entry = zin.getNextEntry(); } } else { in = url.openStream(); } Reader reader = new InputStreamReader(in); XmlPullParser parser = new KXmlParser(); parser.setInput(reader); parseRepository(parser); } catch (MalformedURLException e) { System.out.println("Cannot create connection to url"); } } }
private JarFile getCachedJarFile(URL url) { JarFile result = (JarFile) fileCache.get(url); /* if the JAR file is cached, the permission will always be there */ if (result != null) { Permission perm = getPermission(result); if (perm != null) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { try { sm.checkPermission(perm); } catch (SecurityException se) { // fallback to checkRead/checkConnect for pre 1.2 // security managers if ((perm instanceof java.io.FilePermission) && perm.getActions().indexOf("read") != -1) { sm.checkRead(perm.getName()); } else if ((perm instanceof java.net.SocketPermission) && perm.getActions().indexOf("connect") != -1) { sm.checkConnect(url.getHost(), url.getPort()); } else { throw se; } } } } } return result; }
byte[] getJar(String address) { // System.out.println("getJar: "+address); byte[] data; try { URL url = new URL(address); IJ.showStatus("Connecting to " + IJ.URL); URLConnection uc = url.openConnection(); int len = uc.getContentLength(); if (IJ.debugMode) IJ.log("Updater (url): " + address + " " + len); if (len <= 0) return null; String name = address.contains("wsr") ? "daily build (" : "ij.jar ("; IJ.showStatus("Downloading " + name + IJ.d2s((double) len / 1048576, 1) + "MB)"); InputStream in = uc.getInputStream(); data = new byte[len]; int n = 0; while (n < len) { int count = in.read(data, n, len - n); if (count < 0) throw new EOFException(); n += count; IJ.showProgress(n, len); } in.close(); } catch (IOException e) { if (IJ.debugMode) IJ.log("" + e); return null; } if (IJ.debugMode) IJ.wait(6000); return data; }
public ArrayList<String> parseXML() throws Exception { ArrayList<String> ret = new ArrayList<String>(); handshake(); URL url = new URL( "http://mangaonweb.com/page.do?cdn=" + cdn + "&cpn=book.xml&crcod=" + crcod + "&rid=" + (int) (Math.random() * 10000)); String page = DownloaderUtils.getPage(url.toString(), "UTF-8", cookies); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(page)); Document d = builder.parse(is); Element doc = d.getDocumentElement(); NodeList pages = doc.getElementsByTagName("page"); total = pages.getLength(); for (int i = 0; i < pages.getLength(); i++) { Element e = (Element) pages.item(i); ret.add(e.getAttribute("path")); } return (ret); }
@Override public void run() { try { URL url = buildPingUrl(); if (logger.isDebugEnabled()) { logger.debug("Sending UDC information to {}...", url); } HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout((int) HTTP_TIMEOUT.millis()); conn.setReadTimeout((int) HTTP_TIMEOUT.millis()); if (conn.getResponseCode() >= 300) { throw new Exception( String.format("%s Responded with Code %d", url.getHost(), conn.getResponseCode())); } if (logger.isDebugEnabled()) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = reader.readLine(); while (line != null) { logger.debug(line); line = reader.readLine(); } reader.close(); } else { conn.getInputStream().close(); } successCounter.incrementAndGet(); } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Error sending UDC information", e); } failCounter.incrementAndGet(); } }
public SetIfModifiedSince() throws Exception { serverSock = new ServerSocket(0); int port = serverSock.getLocalPort(); Thread thr = new Thread(this); thr.start(); Date date = new Date(new Date().getTime() - 1440000); // this time yesterday URL url; HttpURLConnection con; // url = new URL(args[0]); url = new URL("http://localhost:" + String.valueOf(port) + "/anything"); con = (HttpURLConnection) url.openConnection(); con.setIfModifiedSince(date.getTime()); con.connect(); int ret = con.getResponseCode(); if (ret == 304) { System.out.println("Success!"); } else { throw new RuntimeException( "Test failed! Http return code using setIfModified method is:" + ret + "\nNOTE:some web servers are not implemented according to RFC, thus a failed test does not necessarily indicate a bug in setIfModifiedSince method"); } }
public static String sendGet(String url, String params) { String result = ""; BufferedReader in = null; try { String urlName = url + "?" + params; URL realUrl = new URL(urlName); URLConnection conn = realUrl.openConnection(); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty( "user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"); conn.connect(); Map<String, List<String>> map = conn.getHeaderFields(); for (String key : map.keySet()) { System.out.println(key + "--->" + map.get(key)); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = in.readLine()) != null) { result += "\n" + line; } } catch (Exception e) { e.printStackTrace(); } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { ex.printStackTrace(); } } return result; }
// callRestfulApi - Calls restful API and returns results as a string public String callRestfulApi( String addr, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); try { ByteArrayOutputStream output = new ByteArrayOutputStream(); URL url = new URL(API_ROOT + addr); URLConnection urlConnection = url.openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { urlConnection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Accept-Charset", "UTF-8"); } IOUtils.copy(urlConnection.getInputStream(), output); String newCookie = getConnectionInfiniteCookie(urlConnection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } return output.toString(); } catch (IOException e) { System.out.println(e.getMessage()); return null; } } // TESTED
/** * ** Gets the 'port' specification in the URI ** @return The 'port' specification in the URL, or * -1 if not port is specified */ public int getPort() { try { URL url = new URL(this.getURI()); return url.getPort(); } catch (MalformedURLException mue) { return -1; } }
/** * ** Gets the 'file' specification in the URI ** @return The 'file' specification in the URL, or * null if unable to determine file */ public String getFile() { try { URL url = new URL(this.getURI()); return url.getFile(); } catch (MalformedURLException mue) { return null; } }
public void start() throws Exception { URL url = new URL("http://localhost:5000/gameInit"); URLConnection urlCon = url.openConnection(); GameInitMessage gim = GameInitMessage.parseFrom(urlCon.getInputStream()); urlCon.getInputStream().close(); this.properties = new PropertyWrapper(gim); gameId = gim.getGameId(); }
static void openURL( JopSession session, String name, boolean newFrame, String frameName, String bookmark) { System.out.println("openURL " + name); Object root = session.getRoot(); // Replace any URL symbol name = replaceUrlSymbol(session, name); try { String url_str = null; if (name.substring(0, 5).equals("http:")) { url_str = name; if (url_str.lastIndexOf(".html") == -1 && url_str.lastIndexOf(".shtml") == -1 && url_str.lastIndexOf(".htm") == -1 && url_str.lastIndexOf(".pdf") == -1) url_str = url_str + ".html"; } else if (name.startsWith("$pwr_doc/")) { URL current = ((JApplet) root).getDocumentBase(); String current_str = current.toString(); int idx1 = current_str.indexOf('/'); if (idx1 != -1 && current_str.length() > idx1 + 1) { idx1 = current_str.indexOf('/', idx1 + 1); if (idx1 != -1 && current_str.length() > idx1 + 1) { idx1 = current_str.indexOf('/', idx1 + 1); if (idx1 != -1 && current_str.length() > idx1 + 1) { url_str = current_str.substring(0, idx1 + 1) + "pwr_doc/" + name.substring(9); if (url_str.lastIndexOf(".html") == -1 && url_str.lastIndexOf(".shtml") == -1 && url_str.lastIndexOf(".htm") == -1 && url_str.lastIndexOf(".pdf") == -1) url_str = url_str + ".html"; } } } } else { URL current = ((JApplet) root).getCodeBase(); String current_str = current.toString(); int idx1 = current_str.lastIndexOf('/'); int idx2 = current_str.lastIndexOf(':'); int idx = idx1; if (idx2 > idx) idx = idx2; String path = current_str.substring(0, idx + 1); if (name.lastIndexOf(".html") == -1 && name.lastIndexOf(".shtml") == -1 && name.lastIndexOf(".htm") == -1 && name.lastIndexOf(".pdf") == -1) url_str = new String(path + name + ".html"); else url_str = new String(path + name); if (bookmark != null) url_str += "#" + bookmark; } System.out.println("Opening URL: " + url_str); URL url = new URL(url_str); AppletContext appCtx = ((JApplet) root).getAppletContext(); if (newFrame) appCtx.showDocument(url, "_blank"); else if (frameName != null) appCtx.showDocument(url, frameName); else appCtx.showDocument(url, "_self"); } catch (MalformedURLException e) { System.out.println("MalformedURL : " + name); } }
public static void main(String[] argv) { try { URL url = new URL(argv[0]); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); MarkupReader mr = new MarkupReader(br, new AceViewerConfig(), false); } catch (Exception e) { System.err.println(e); // debug } }
public InputStream getResourceAsStream(String path) { URL url = getResource(path); if (url == null) return null; try { return url.openStream(); } catch (IOException ioe) { throw new RuntimeException("can't getResourceAsStream [" + path + "]", ioe); } }
public static ModuleImpl loadModule(String resource) throws IOException, CoreException { URL url = ModuleSyncRunnerTest.class.getResource(resource); if (url == null) { Assert.fail("resource not found: " + resource); } ModuleImpl module = new ModuleManifestParser().parse(url.openStream()); module.setLocation(url); return module; }
protected void addPathFile(final File pathComponent) throws IOException { if (!this.pathComponents.contains(pathComponent)) { this.pathComponents.addElement(pathComponent); } if (pathComponent.isDirectory()) { return; } final String absPathPlusTimeAndLength = pathComponent.getAbsolutePath() + pathComponent.lastModified() + "-" + pathComponent.length(); String classpath = AntClassLoader.pathMap.get(absPathPlusTimeAndLength); if (classpath == null) { JarFile jarFile = null; try { jarFile = new JarFile(pathComponent); final Manifest manifest = jarFile.getManifest(); if (manifest == null) { return; } classpath = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH); } finally { if (jarFile != null) { jarFile.close(); } } if (classpath == null) { classpath = ""; } AntClassLoader.pathMap.put(absPathPlusTimeAndLength, classpath); } if (!"".equals(classpath)) { final URL baseURL = AntClassLoader.FILE_UTILS.getFileURL(pathComponent); final StringTokenizer st = new StringTokenizer(classpath); while (st.hasMoreTokens()) { final String classpathElement = st.nextToken(); final URL libraryURL = new URL(baseURL, classpathElement); if (!libraryURL.getProtocol().equals("file")) { this.log( "Skipping jar library " + classpathElement + " since only relative URLs are supported by this" + " loader", 3); } else { final String decodedPath = Locator.decodeUri(libraryURL.getFile()); final File libraryFile = new File(decodedPath); if (!libraryFile.exists() || this.isInPath(libraryFile)) { continue; } this.addPathFile(libraryFile); } } } }
public static void main(String[] args) throws IOException { URLConnectionTest u = new URLConnectionTest(); String urlName = "http://localhost/~huahan/PPServer/index.php/blog/index"; URL url = new URL(urlName); URLConnection connection = url.openConnection(); connection.connect(); for (int i = 0; i < 10; i++) u.fun(connection); }
private void doImportFromURL(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { URL source = getSourceURL(); IOUtilities.pipe( source.openStream(), new FileOutputStream(new File(getStorageDirectory(), FILE_DATA), true), true, true); completeTransfer(req, resp); }
/** * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件 * * @param task * @return "ok" if download success (else return errmessage); */ static String download(DownloadTask task) { if (!openedStatus && show) openStatus(); URL url; HttpURLConnection conn; try { url = new URL(task.getOrigin()); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/" + Math.random()); if ("www.imgjav.com".equals(url.getHost())) { // 该网站需要带cookie请求 conn.setRequestProperty( "User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/537.36"); // conn.setRequestProperty("Cookie", "__cfduid=d219ea333c7a9b5743b572697b631925a1446093229; // cf_clearance=6ae62d843f5d09acf393f9e4eb130d9366840c82-1446093303-28800"); conn.setRequestProperty( "Cookie", "__cfduid=d6ee846b378bb7d5d173a05541f8a2b6a1446090548; cf_clearance=ea10e8db31f8b6ee51570b118dd89b7e616d7b62-1446099714-28800"); conn.setRequestProperty("Host", "www.imgjav.com"); } Path directory = Paths.get(task.getDest()).getParent(); if (!Files.exists(directory)) Files.createDirectories(directory); } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } try (InputStream is = conn.getInputStream(); BufferedInputStream in = new BufferedInputStream(is); FileOutputStream fos = new FileOutputStream(task.getDest()); OutputStream out = new BufferedOutputStream(fos); ) { int length = conn.getContentLength(); if (length < 1) throw new IOException("length<1"); byte[] binary = new byte[length]; byte[] buff = new byte[65536]; int len; int index = 0; while ((len = in.read(buff)) != -1) { System.arraycopy(buff, 0, binary, index, len); index += len; allLen += len; // allLen有线程安全的问题 ,可能会不正确。无需精确数据,所以不同步了 task.setReceivePercent(String.format("%.2f", ((float) index / length) * 100) + "%"); } out.write(binary); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } return "ok"; }