Java访问Tomcat图片资源
环境
CentOS Linux release 8.1.1911 (Core)
java 14.0.2 2020-07-14
Java(TM) SE Runtime Environment (build 14.0.2+12-46)
Java HotSpot(TM) 64-Bit Server VM (build 14.0.2+12-46, mixed mode, sharing)
apache-tomcat-9.0.38
实现代码
读取Tomcat
主目录下./webapps/ROOT
目录下默认存在的图片tomcat.png
其中,<host_name>
为服务器主机名(IP地址),PORT
为端口号,Tomcat
默认使用8080
,使用阿里云、腾讯云等服务器需要在安全组配置中设置内网入方向规则
package com.demo.tomcat;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Tomcat {
private static String HOST_NAME = "http://<host name>";
private static int PORT = 8080;
public void getImage(String filePath) {
String path = String.format(HOST_NAME + ":%d/", PORT) + filePath;
URL url = null;
try {
url = new URL(path);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setConnectTimeout(5000);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(true);
if (httpURLConnection.getResponseCode() == 200) {
InputStream inputStream = httpURLConnection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream("./res/tomcat.jpg");
System.out.println("Request succeed!");
saveImage(fileOutputStream, inputStream);
System.out.println("Save Image succeed!");
} else {
System.out.println("Request failed!");
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void saveImage(FileOutputStream fileOutputStream, InputStream inputStream) {
int length;
byte buffer[] = new byte[1024];
while (true) {
try {
if ((length = inputStream.read(buffer)) == -1) {
break;
}
fileOutputStream.write(buffer, 0, length);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Tomcat tomcat = new Tomcat();
tomcat.getImage("tomcat.png");
}
}
测试结果
路径./res/tomcat.png
最后
- 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!