1. Download the client code
package javadownload; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * @Description Export virtual machine* @author wxt * @version 1.0 * @since */ public class GetVM { /** * Test* @param args */ public static void main(String[] args) { String url = "http://192.168.5.102:8845/xx"; byte[] btImg = getVMFromNetByUrl(url); if(null != btImg && btImg.length > 0){ System.out.println("Read to: " + btImg.length + " Byte"); String fileName = "ygserver"; writeImageToDisk(btImg, fileName); }else{ System.out.println("No content obtained from this connection"); } } /** * Write vm to disk* @param vm Data stream* @param fileName Name of the file when saving*/ public static void writeImageToDisk(byte[] vm, String fileName){ try { File file = new File("./" + fileName); FileOutputStream fops = new FileOutputStream(file); fops.write(vm); fops.flush(); fops.close(); System.out.println("Download Complete"); } catch (Exception e) { e.printStackTrace(); } } /** * Get data from address* @param strUrl Network connection address* @return */ public static byte[] getVMFromNetByUrl(String strUrl){ try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();//Get data through input stream byte[] btImg = readInputStream(inStream);//The binary data obtained returns btImg; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Get data from the input stream* @param inStream Input stream* @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception{ ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=inStream.read(buffer)) != -1 ){ outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } }The above code is only suitable for downloading small files. If you download a large file, an Exception in thread "main" java.lang.OutOfMemoryError: Java heap space error, so if you need to modify the above code when downloading a large file, the code is as follows:
package javadownload; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * @Description Export virtual machine* @author wxt * @version 1.0 * @since */ public class GetBigFile { /** * Test* @param args */ public static void main(String[] args) { String url = "http://192.168.5.76:8080/export?uuid=123"; String fileName="yserver"; getVMFromNetByUrl(url,fileName); } /** * Download file based on the address* @param strUrl Network connection address* @param fileName Storage name of the download file*/ public static void getVMFromNetByUrl(String strUrl,String fileName){ try { URL url = new URL(strUrl); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); InputStream inStream = conn.getInputStream();//Get data through input stream byte[] buffer = new byte[4096]; int len = 0; File file = new File("./" + fileName); FileOutputStream fops = new FileOutputStream(file); while( (len=inStream.read(buffer)) != -1 ){ fops.write(buffer, 0, len); } fops.flush(); fops.close(); } catch (Exception e) { e.printStackTrace(); } } }2. Upload file client:
package javadownload; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUpload { /** * Send request* * @param url * Request address* @param filePath * The file is saved on the server (here is written for the convenience of testing, you can remove this parameter) * @return * @throws IOException */ public int send(String url, String filePath) throws IOException { File file = new File(filePath); if (!file.exists() || !file.isFile()) { return -1; } /** * Part 1*/ URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); /** * Set key value */ con.setRequestMethod("POST"); // Submit the form in Post mode, default get method con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); // Post mode cannot use cache// Set request header information con.setRequestProperty("Connection", "close"); // Keep-Alive con.setRequestProperty("Charset", "UTF-8"); // Set boundary String BOUNDARY = "------------" + System.currentTimeMillis(); con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY); // Request body information// Part 1: StringBuilder sb = new StringBuilder(); sb.append("--"); // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////Content-Disposition: form-data;name=/"file_name/;filename=/"" + file.getName() + "/"/"/r/n"); sb.append("Content-Type:application/octet-stream/r/n/r/n"); sb.append("Connection:close/r/n/r/n"); byte[] head = sb.toString().getBytes("utf-8"); // Get the output stream OutputStream out = new DataOutputStream(con.getOutputStream()); out.write(head); // File body part DataInputStream in = new DataInputStream(new FileInputStream(file)); int bytes = 0; byte[] bufferOut = new byte[1024]; while ((bytes = in.read(bufferOut)) != -1) { out.write(bufferOut, 0, bytes); } in.close(); // The ending part byte[] foot = ("/r/n--" + BOUNDARY + "--/r/n").getBytes("utf-8");// Define the last data divider out.write(foot); out.flush(); out.close(); /** * Read the server response, it must be read, otherwise the submission will not be successful*/ return con.getResponseCode(); /** * The following method is OK to read*/ // try { // // Define the BufferedReader input stream to read the URL response// BufferedReader reader = new BufferedReader(new InputStreamReader( // con.getInputStream())); // String line = null; // while ((line = reader.readLine()) != null) { // System.out.println(line); // } // } catch (Exception e) { // System.out.println("Exception occurred when sending a POST request!" + e); // e.printStackTrace(); // } } public static void main(String[] args) throws IOException { FileUpload up = new FileUpload(); System.out.println(up.send("http://192.168.5.102:8845/xx", "./vif.xml")); ; } }Summarize
The above is the example code for downloading file client and uploading file client under Java introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!