Java访问Tomcat图片资源

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

最后

  • 由于博主水平有限,不免有疏漏之处,欢迎读者随时批评指正,以免造成不必要的误解!
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值