下面是一个用 Java 编写的上传文件的示例代码:
import java.io.*;
import java.net.*;
import java.util.*;
public class FileUpload {
public static void main(String[] args) throws Exception {
String fileName = "test.txt";
String urlString = "http://www.example.com/upload";
// Create a URL object
URL url = new URL(urlString);
// Open a connection to the URL
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to "POST"
connection.setRequestMethod("POST");
// Set the request properties
connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setRequestProperty("Content-Length", String.valueOf(new File(fileName).length()));
// Enable output
connection.setDoOutput(true);
// Open a output stream to the server
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
// Open an input stream to the file
FileInputStream inputStream = new FileInputStream(fileName);
// Read the contents of the file into a byte array
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
// Write the bytes to the output stream
outputStream.write(buffer, 0, bytesRead);
}
// Close the input and output streams
inputStream.close();
outputStream.close();
// Get the response code from the server
int responseCode = connection.getResponseCode();
System.out.println("Response code: " + responseCode);
// Read the response from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
下面是一个用 Java 编写的下载文件的示例代码:
``` import java.io.; import java.net.;
public class FileDownload { public static void main(String[] args) throws Exception { String fileUrl = "http://www.example.com/download/test.txt"; String fileName = "test.txt";
// Open a connection to the URL
URL url = new URL(fileUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// Set the request method to "GET"
connection.setRequestMethod("GET");
// Open an input stream to the file
InputStream inputStream = connection.getInputStream();
// Create a file output stream
FileOutputStream outputStream = new FileOutputStream(fileName);
// Read the contents of the file into a byte array
byte[] buffer = new byte[1024];
int