Java http download file client and upload file client instance code
- 2020-12-07 04:01:44
- OfStack
1. Download 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;
/**
* @ instructions Exported 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: " + btImg.length + " byte ");
String fileName = "ygserver";
writeImageToDisk(btImg, fileName);
}else{
System.out.println(" No content was obtained from the connection ");
}
}
/**
* will vm Write to disk
* @param vm The data flow
* @param fileName Name of the file when it was saved
*/
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(" The download is complete ");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* A byte stream that retrieves data based on 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 the data from the input stream
byte[] btImg = readInputStream(inStream);// To get the 2 Hexadecimal data
return btImg;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* Get the data from the input stream
* @param inStream The 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();
}
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space error will appear if you download a large file. Therefore, you need to modify the above code if you download 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;
/**
* @ instructions Exported 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 the document by address
* @param strUrl Network connection address
* @param fileName The storage name of the downloaded 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 the data from the 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 the request
*
* @param url
* Request the address
* @param filePath
* Save the path to the file on the server (write it here for your own testing convenience, 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;
}
/**
* The first 1 Part of the
*/
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection) urlObj.openConnection();
/**
* Set key values
*/
con.setRequestMethod("POST"); // In order to Post Method to submit the form, default get way
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false); // post Method cannot use cache
// Set the request header information
con.setRequestProperty("Connection", "close");//Keep-Alive
con.setRequestProperty("Charset", "UTF-8");
// Set the boundary
String BOUNDARY = "----------" + System.currentTimeMillis();
con.setRequestProperty("Content-Type", "multipart/form-data; boundary="
+ BOUNDARY);
// Request body information
// The first 1 Parts:
StringBuilder sb = new StringBuilder();
sb.append("--"); // //////// There must be two more lines
sb.append(BOUNDARY);
sb.append("\r\n");
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 output stream
OutputStream out = new DataOutputStream(con.getOutputStream());
out.write(head);
// Body of the document
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 final data delimiter
out.write(foot);
out.flush();
out.close();
/**
* Read server response, must read , Otherwise the submission will not succeed
*/
return con.getResponseCode();
/**
* It is also possible to read the following way
*/
// try {
// // define BufferedReader Input stream to read URL The response of the
// 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(" send POST Request exception! " + 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"));
;
}
}
conclusion