java request 获取文件
时间: 2024-01-27 11:05:16 浏览: 15
要获取文件,可以使用Java中的HttpURLConnection类来发送HTTP请求并获取文件。下面是一个简单的示例代码:
```
URL url = new URL("http://example.com/file.pdf");
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
FileOutputStream outputStream = new FileOutputStream("file.pdf");
int bytesRead = -1;
byte[] buffer = new byte[4096];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("Server returned response code: " + responseCode);
}
```
需要替换示例代码中的URL和文件名,以便适应您的需求。还需要处理IOException异常。