public static void main(String args[]) { int size = 1024; File site = new File("site.html"); OutputStream outStream = null; InputStream is; try { URL url; byte[] buf; int ByteRead; url = new URL( "http://zakupki.gov.ru/epz/order/notice/ea44/view/common-info.html?regNumber=0148300015814000370"); System.out.println(url.getFile()); outStream = new BufferedOutputStream(new FileOutputStream(site)); URLConnection uCon = url.openConnection(); is = uCon.getInputStream(); buf = new byte[size]; while ((ByteRead = is.read(buf)) != -1) { outStream.write(buf, 0, ByteRead); } System.out.println("Downloaded Successfully."); } catch (Exception e) { e.printStackTrace(); } }
private static FileItem prepareFileItemFromInputStream( PipelineContext pipelineContext, InputStream inputStream, int scope) { // Get FileItem final FileItem fileItem = prepareFileItem(pipelineContext, scope); // Write to file OutputStream os = null; try { os = fileItem.getOutputStream(); copyStream(inputStream, os); } catch (IOException e) { throw new OXFException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { throw new OXFException(e); } } } // Create file if it doesn't exist (necessary when the file size is 0) final File storeLocation = ((DiskFileItem) fileItem).getStoreLocation(); try { storeLocation.createNewFile(); } catch (IOException e) { throw new OXFException(e); } return fileItem; }
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; } }
private static void writePostReply(HttpExchange msg, byte[] buf) throws Exception { msg.getResponseHeaders().add("Content-Type", "text/xml"); msg.sendResponseHeaders(200, buf.length); OutputStream out = msg.getResponseBody(); out.write(buf); out.close(); }
public static void main(String[] args) throws IOException { int servPort = Integer.parseInt(args[0]); ServerSocket servSock = new ServerSocket(8080); // cria o socket servidor int recvMsgSize; // tamanho da msg byte[] byteBuffer = new byte[BufSize]; // buffer de recebimento for (; ; ) { // espera as solicitações dos clientes Socket clntSock = servSock.accept(); // server aceita a conexão // imprimi o ip e a porta do servidor System.out.println( "Controlando o cliente" + clntSock.getInetAddress().getHostAddress() + "na porta" + clntSock.getPort()); InputStream in = clntSock.getInputStream(); OutputStream out = clntSock.getOutputStream(); while ((recvMsgSize = in.read(byteBuffer)) != -1) // lê a msg a ser transmitida até estourar o tamanho out.write(byteBuffer, 0, recvMsgSize); clntSock.close(); // fecha o socket do cliente } }
public void copyFile(String file1, String file2) { InputStream inStream = null; OutputStream outStream = null; try { File afile = new File(file1); File bfile = new File(file2); inStream = new FileInputStream(afile); outStream = new FileOutputStream(bfile); byte[] buffer = new byte[1024]; int length; // copy the file content in bytes while ((length = inStream.read(buffer)) > 0) { outStream.write(buffer, 0, length); } inStream.close(); outStream.close(); System.out.println("File is copied successful!"); } catch (IOException e) { e.printStackTrace(); } }
/** * ** Writes the specified byte array to the specified socket's output stream ** @param socket The * socket which's output stream to write to ** @param b The byte array to write to the socket * output stream ** @throws IOException if an error occurs */ protected static void socketWriteBytes(Socket socket, byte b[]) throws IOException { if ((socket != null) && (b != null)) { OutputStream output = socket.getOutputStream(); output.write(b); output.flush(); } }
private boolean userPassAuth() throws IOException { int ver = in.read(); int ulen = in.read(); if (ulen <= 0) throw new SocketException("SOCKS protocol error"); byte[] buf = new byte[ulen]; readBuf(in, buf); String uname = new String(buf); String password = null; ulen = in.read(); if (ulen < 0) throw new SocketException("SOCKS protocol error"); if (ulen > 0) { buf = new byte[ulen]; readBuf(in, buf); password = new String(buf); } // Check username/password validity here System.err.println("User: '******'" + password); if (users.containsKey(uname)) { String p1 = users.get(uname); System.err.println("p1 = " + p1); if (p1.equals(password)) { out.write(PROTO_VERS); out.write(REQUEST_OK); out.flush(); return true; } } out.write(PROTO_VERS); out.write(NOT_ALLOWED); out.flush(); return false; }
public AuthenticatedSocket(InetAddress ia, int port, MessageDigest md, byte[] secret) throws IOException, AuthenticationException { super(ia, port); try { OutputStream output = this.getOutputStream(); InputStream input = this.getInputStream(); // Get challenge length byte[] challengeSize = new byte[4]; input.read(challengeSize); // Receive random challenge string byte[] challenge = new byte[Bytes.toInt(challengeSize)]; input.read(challenge); // Generate MD5 hash byte[] append = Bytes.append(challenge, secret); byte[] hash = md.digest(append); // Send time and hash strings output.write(hash); } catch (Exception e) { throw new AuthenticationException("Authentication failed: " + e.getMessage()); } }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); for (int i = 0; i < 10; i++) { sslOS.write(280); sslOS.flush(); sslIS.read(); } for (int i = 0; i < 10; i++) { sslOS.write(280); sslOS.flush(); sslIS.read(); } sslSocket.close(); }
private void passTcpFileDescriptor( LocalSocket fdSocket, OutputStream outputStream, String socketId, String dstIp, int dstPort, int connectTimeout) throws Exception { Socket sock = new Socket(); sock.setTcpNoDelay(true); // force file descriptor being created if (protect(sock)) { try { sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout); ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock); tcpSockets.put(socketId, sock); fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()}); outputStream.write('*'); outputStream.flush(); fd.detachFd(); } catch (ConnectException e) { LogUtils.e("connect " + dstIp + ":" + dstPort + " failed"); outputStream.write('!'); sock.close(); } catch (SocketTimeoutException e) { LogUtils.e("connect " + dstIp + ":" + dstPort + " failed"); outputStream.write('!'); sock.close(); } finally { outputStream.flush(); } } else { LogUtils.e("protect tcp socket failed"); } }
// postToRestfulApi - // Note: params in the addr field need to be URLEncoded private String postToRestfulApi( String addr, String data, HttpServletRequest request, HttpServletResponse response) { if (localCookie) CookieHandler.setDefault(cm); String result = ""; try { URLConnection connection = new URL(API_ROOT + addr).openConnection(); String cookieVal = getBrowserInfiniteCookie(request); if (cookieVal != null) { connection.addRequestProperty("Cookie", "infinitecookie=" + cookieVal); connection.setDoInput(true); } connection.setDoOutput(true); connection.setRequestProperty("Accept-Charset", "UTF-8"); // Post JSON string to URL OutputStream os = connection.getOutputStream(); byte[] b = data.getBytes("UTF-8"); os.write(b); // Receive results back from API InputStream is = connection.getInputStream(); result = IOUtils.toString(is, "UTF-8"); String newCookie = getConnectionInfiniteCookie(connection); if (newCookie != null && response != null) { setBrowserInfiniteCookie(response, newCookie, request.getServerPort()); } } catch (Exception e) { // System.out.println("Exception: " + e.getMessage()); } return result; } // TESTED
/** * Checks if a given file exists and, if not, create it by copying a default template from * resources; used to create default conf files. * * @param file The path of the file that needs to exist * @param template The path of the template for the file */ public static void ensureFileExists(final String file, final String template) { if (LAUNCHED_FROM_JAR && !Files.exists(Paths.get(file))) { if (Debug.on) printDebug("[Meta] " + file + " does not exist: creating a default one."); InputStream stream = Meta.class.getResourceAsStream(template); if (stream == null) { printDebug( "[ WARNING ] template for " + template + " not found. Won't create a default " + file + "."); } else { int readBytes; byte[] buffer = new byte[4096]; try (OutputStream outStream = new FileOutputStream(new File(file))) { while ((readBytes = stream.read(buffer)) > 0) { outStream.write(buffer, 0, readBytes); } if (Debug.on) printDebug("[Meta] created default file " + file + " from " + template + "."); } catch (IOException e) { e.printStackTrace(); } finally { try { stream.close(); } catch (IOException ignore) { } } } } else { if (Meta.LAUNCHED_FROM_JAR && Debug.on) printDebug("[Meta] file exists: " + file + "."); } }
/** * Method to update database on the server with new and changed hazards given as a JSONObject * instance * * @param uploadHazards A JSONObject instance with encoded new and update hazards * @throws IOException */ public static void uploadHazards(JSONObject uploadHazards) throws IOException { // upload hazards in json to php (to use json_decode) // Hazard parameter should be encoded as json already // Set Post connection URL url = new URL(site + "/update.php"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestMethod("POST"); OutputStream writer = conn.getOutputStream(); writer.write( uploadHazards.toString().getBytes("UTF-8")); // toString produces compact JSONString // no white space writer.close(); // read response (success / error) BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuffer response = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); }
public void sendMessage(String message) { checkConnected(); HttpURLConnection outcomeConnection = null; try { CLIENT_LOGGER.info("start sending message \"" + message + "\""); outcomeConnection = prepareOutputConnection(); byte[] buffer = MessageHelper.buildSendMessageRequestBody(message).getBytes(); OutputStream outputStream = outcomeConnection.getOutputStream(); outputStream.write(buffer, 0, buffer.length); outputStream.close(); outcomeConnection.getInputStream(); // to send data to server CLIENT_LOGGER.info("message sent"); } catch (ConnectException e) { logger.error("Connection error. Disconnecting...", e); CLIENT_LOGGER.error("connection error", e); disconnect(); } catch (IOException e) { CLIENT_LOGGER.error("IOException", e); logger.error("IOException occurred while sending message", e); } finally { if (outcomeConnection != null) { outcomeConnection.disconnect(); } CLIENT_LOGGER.info("stop sending message \"" + message + "\""); } }
private void invokeJsp() throws Exception { Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/jsp/test1.jsp" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); BufferedReader bis = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = bis.readLine()) != null) { if (line.startsWith("Location:")) { break; } } if (line != null) { System.out.println(line); // Check the path if (line.startsWith("Location: " + PATH)) { fail = false; } else { System.err.println("Wrong path: " + line + ", expected: " + PATH); stat.addStatus(TEST_NAME, stat.FAIL); fail = true; } } else { System.err.println("Missing Location response header"); stat.addStatus(TEST_NAME, stat.FAIL); } }
public static void main(String[] args) { try { Socket s1 = new Socket("127.0.0.1", 57643); InputStream is = s1.getInputStream(); DataInputStream dis = new DataInputStream(is); System.out.println(dis.readUTF()); OutputStream os = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream(os); dos.writeUTF("Oh my gosh..."); dis.close(); is.close(); dos.close(); os.close(); s1.close(); } catch (ConnectException connExc) { connExc.printStackTrace(); System.out.println("Server connection failed"); } catch (IOException ioExc) { ioExc.printStackTrace(); } }
// Send File public void sendFile(String chunkName) throws IOException { OutputStream os = null; String currentDir = System.getProperty("user.dir"); chunkName = currentDir + "/src/srcFile/" + chunkName; File myFile = new File(chunkName); byte[] arrby = new byte[(int) myFile.length()]; try { FileInputStream fis = new FileInputStream(myFile); BufferedInputStream bis = new BufferedInputStream(fis); bis.read(arrby, 0, arrby.length); os = csocket.getOutputStream(); System.out.println("Sending File."); os.write(arrby, 0, arrby.length); os.flush(); System.out.println("File Sent."); // os.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { // os.close(); } }
public void firstRun() throws Exception { Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/test.jsp" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); // Get the JSESSIONID from the response String line = null; while ((line = br.readLine()) != null) { System.out.println(line); if (line.startsWith("Set-Cookie:") || line.startsWith("Set-cookie:")) { break; } } if (line == null) { throw new Exception("Missing Set-Cookie response header"); } String jsessionId = getSessionIdFromCookie(line, JSESSIONID); // Store the JSESSIONID in a file FileOutputStream fos = new FileOutputStream(JSESSIONID); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(jsessionId); osw.close(); stat.addStatus(TEST_NAME, stat.PASS); }
public Server() { try { ServerSocket ss = new ServerSocket(SERVER_PORT); Socket s = ss.accept(); InputStream is = s.getInputStream(); OutputStream out = s.getOutputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String sss = br.readLine(); System.out.println(sss); PrintWriter pw = new PrintWriter(out); pw.print("hello,我是服务器。"); pw.close(); br.close(); isr.close(); out.close(); is.close(); s.close(); ss.close(); } catch (UnknownHostException ue) { ue.printStackTrace(); } catch (IOException oe) { oe.printStackTrace(); } }
private void downloadInternal(URI address, File destination) throws Exception { OutputStream out = null; URLConnection conn; InputStream in = null; try { URL url = address.toURL(); out = new BufferedOutputStream(new FileOutputStream(destination)); conn = url.openConnection(); final String userAgentValue = calculateUserAgent(); conn.setRequestProperty("User-Agent", userAgentValue); in = conn.getInputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int numRead; long progressCounter = 0; while ((numRead = in.read(buffer)) != -1) { progressCounter += numRead; if (progressCounter / PROGRESS_CHUNK > 0) { System.out.print("."); progressCounter = progressCounter - PROGRESS_CHUNK; } out.write(buffer, 0, numRead); } } finally { System.out.println(""); if (in != null) { in.close(); } if (out != null) { out.close(); } } }
public void secondRun() throws Exception { // Read the JSESSIONID from the previous run FileInputStream fis = new FileInputStream(JSESSIONID); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String jsessionId = br.readLine(); new File(JSESSIONID).delete(); Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/ResumeSession" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); String cookie = "Cookie: " + jsessionId + "\n"; os.write(cookie.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String line = null; boolean found = false; while ((line = br.readLine()) != null) { System.out.println(line); if (line.contains(EXPECTED_RESPONSE)) { found = true; break; } } if (found) { stat.addStatus(TEST_NAME, stat.PASS); } else { throw new Exception("Wrong response. Expected response: " + EXPECTED_RESPONSE + " not found"); } }
public static void ensureExists(File thing, String resource) { System.err.println("configfile = " + thing); if (!thing.exists()) { try { System.err.println("Creating: " + thing + " from " + resource); if (resource.indexOf("/") != 0) { resource = "/" + resource; } InputStream is = Config.class.getResourceAsStream(resource); if (is == null) { throw new NullPointerException("Can't find resource: " + resource); } getParentFile(thing).mkdirs(); OutputStream os = new FileOutputStream(thing); for (int next = is.read(); next != -1; next = is.read()) { os.write(next); } os.flush(); os.close(); } catch (FileNotFoundException fnfe) { throw new Error("Can't create resource: " + fnfe.getMessage()); } catch (IOException ioe) { throw new Error("Can't create resource: " + ioe.getMessage()); } } }
/** * 请求xml数据 * * @param url * @param soapAction * @param xml * @return */ public static String sendXMl(String url, String soapAction, String xml) { HttpURLConnection conn = null; InputStream in = null; InputStreamReader isr = null; OutputStream out = null; StringBuffer result = null; try { byte[] sendbyte = xml.getBytes("UTF-8"); URL u = new URL(url); conn = (HttpURLConnection) u.openConnection(); conn.setRequestProperty("Content-Type", "text/xml; charset=utf-8"); conn.setRequestProperty("SOAPAction", soapAction); conn.setRequestProperty("Content-Length", sendbyte.length + ""); conn.setDoInput(true); conn.setDoOutput(true); conn.setConnectTimeout(5000); conn.setReadTimeout(5000); out = conn.getOutputStream(); out.write(sendbyte); if (conn.getResponseCode() == 200) { result = new StringBuffer(); in = conn.getInputStream(); isr = new InputStreamReader(in, "UTF-8"); char[] c = new char[1024]; int a = isr.read(c); while (a != -1) { result.append(new String(c, 0, a)); a = isr.read(c); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } try { if (in != null) { in.close(); } if (isr != null) { isr.close(); } if (out != null) { out.close(); } } catch (IOException e) { e.printStackTrace(); } } return result == null ? null : result + ""; }
public static String httsRequest(String url, String contentdata) { String str_return = ""; SSLContext sc = null; try { sc = SSLContext.getInstance("SSL"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } try { sc.init( null, new TrustManager[] {new TrustAnyTrustManager()}, new java.security.SecureRandom()); } catch (KeyManagementException e) { e.printStackTrace(); } URL console = null; try { console = new URL(url); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } HttpsURLConnection conn; try { conn = (HttpsURLConnection) console.openConnection(); conn.setRequestMethod("POST"); conn.setSSLSocketFactory(sc.getSocketFactory()); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setRequestProperty("Accept", "application/json"); conn.setDoInput(true); conn.setDoOutput(true); // contentdata="username=arcgis&password=arcgis123&client=requestip&f=json" String inpputs = contentdata; OutputStream os = conn.getOutputStream(); os.write(inpputs.getBytes()); os.close(); conn.connect(); InputStream is = conn.getInputStream(); // // DataInputStream indata = new DataInputStream(is); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String ret = ""; while (ret != null) { ret = reader.readLine(); if (ret != null && !ret.trim().equals("")) { str_return = str_return + ret; } } is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return str_return; }
/** * ** Writes <code>length</code> bytes from the specified byte array ** starting at <code>offset * </code> to the specified socket's output stream. ** @param socket The socket which's output * stream to write to ** @param b The byte array to write to the socket output stream ** @param * offset The start offset in the data to begin writing at ** @param length The length of the * data. Normally <code>b.length</code> ** @throws IOException if an error occurs */ protected static void socketWriteBytes(Socket socket, byte b[], int offset, int length) throws IOException { if ((socket != null) && (b != null)) { int bofs = offset; int blen = (length >= 0) ? length : b.length; OutputStream output = socket.getOutputStream(); output.write(b, bofs, blen); output.flush(); } }
/** * Writes an address to the SOCKS connection in domain-name format (including sending the type * field). * * @param host Host name * @param port Port * @throws IOException */ protected void writeAddress(String host, int port) throws IOException { output.write(3); // Domain name // Actual name output.write(host.length()); output.write(host.getBytes("ISO-8859-1")); // Port in network byte order int port1 = port >> 8, port2 = port & 0xff; output.write(port1); output.write(port2); }
public void run() { try { InputStream in; OutputStream out; try { in = sk.getInputStream(); out = sk.getOutputStream(); } catch (IOException e) { throw (new RuntimeException(e)); } while (true) { try { int len = Utils.int32d(read(in, 4), 0); if (!auth && (len > 256)) return; Message msg = new MessageBuf(read(in, len)); String cmd = msg.string(); Object[] args = msg.list(); Object[] reply; if (auth) { Command cc = commands.get(cmd); if (cc != null) reply = cc.run(this, args); else reply = new Object[] {"nocmd"}; } else { if (cmd.equals("nonce")) { reply = new Object[] {nonce}; } else if (cmd.equals("auth")) { if (Arrays.equals((byte[]) args[0], ckey)) { reply = new Object[] {"ok"}; auth = true; } else { reply = new Object[] {"no"}; } } else { return; } } MessageBuf rb = new MessageBuf(); rb.addlist(reply); byte[] rbuf = new byte[4 + rb.size()]; Utils.uint32e(rb.size(), rbuf, 0); rb.fin(rbuf, 4); out.write(rbuf); } catch (IOException e) { return; } } } catch (InterruptedException e) { } finally { try { sk.close(); } catch (IOException e) { throw (new RuntimeException(e)); } } }
/** * 以阻塞的方式立即下载一个文件,该方法会覆盖已经存在的文件 * * @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"; }
public static void main(String[] args) throws Exception { // 创建客户端的socket服务。指定目的主机和端口 Socket s = new Socket("192.168.1.254", 10003); // 为了发送数据,应该获取socket流中的输出流。 OutputStream out = s.getOutputStream(); out.write("tcp ge men lai le ".getBytes()); s.close(); }