Java跨服务器上传下载文件
时间: 2023-05-31 11:02:27 浏览: 68
Java可以使用HTTP协议进行跨服务器文件上传和下载。以下是一个简单的示例代码:
文件上传:
```java
public void uploadFile(String urlStr, String filePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + "---------------------------7d4a6d158c9");
OutputStream out = conn.getOutputStream();
FileInputStream fileInputStream = new FileInputStream(filePath);
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = fileInputStream.read(buffer, 0, 8192)) != -1) {
out.write(buffer, 0, bytesRead);
}
out.close();
fileInputStream.close();
conn.getResponseCode();
}
```
文件下载:
```java
public void downloadFile(String urlStr, String filePath) throws IOException {
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoOutput(true);
InputStream in = conn.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
byte[] buffer = new byte[8192];
int bytesRead = 0;
while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
fileOutputStream.write(buffer, 0, bytesRead);
}
fileOutputStream.close();
in.close();
conn.disconnect();
}
```
需要注意的是,上传和下载的URL需要指向正确的服务器地址和文件路径。另外,上传需要设置正确的Content-Type和boundary。