【问题标题】:Server gives 500 code error but still serves content服务器给出 500 代码错误但仍提供内容
【发布时间】:2018-06-20 04:35:27
【问题描述】:

我正在使用此功能提供“serveraddress/img/:imageid”:

 public static String getImage(Request req, Response res) {
        String imageId = req.params("imageid");
        byte[] bytes = readImage("img/" + imageId);

        return Base64.getMimeEncoder().encodeToString(bytes); 
    }

 public static byte[] readImage(String image) {
        byte[] bytes;
        try {
            File fff = new File(image);
            FileInputStream fileInputStream = new FileInputStream(fff);
            long byteLength = fff.length();

            bytes = new byte[(int) byteLength];
            fileInputStream.read(bytes, 0, (int) byteLength);
        } catch (Exception ex) {
            ex.printStackTrace();
            bytes = null;
        }
        return bytes;
    }

对于前几个请求,它正常交付。但是当更多的,比如 5 或 6 个请求请求图像时,它开始发送服务器错误代码 500,而没有任何堆栈跟踪。我不确定问题是什么,但我希望有人能帮我弄清楚。

这是我的 gradle.build 文件,供任何想要测试的人使用:

testCompile group: 'junit', name: 'junit', version: '4.12'
compile group: 'org.slf4j', name: 'slf4j-log4j12', version: '1.7.21'
compile "com.sparkjava:spark-core:2.7.1"

这也是主要功能:

public static void main(String[] args) {
        BasicConfigurator.configure();
        org.apache.log4j.Logger.getRootLogger().setLevel(Level.ERROR);
        port(8883);
        get("/img/:imageid", this::getImage);
}

【问题讨论】:

    标签: image api http uploading spark-java


    【解决方案1】:

    看起来您的代码从未关闭它使用的FileInputStream,因此您正在泄漏文件描述符和内存。您应该使用 try-with-resources 或在 finally 块中关闭它们(顺便说一句,也许您可​​以使用 linter 来警告您未关闭的资源)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-23
      • 2014-10-16
      相关资源
      最近更新 更多