0

我在java中有一个这样的Web服务器:

public static void main(String[] args) throws Exception {
   HttpServer server = HttpServer.create(new InetSocketAddress(80), 0);
   server.createContext("/", new HomeHandler());
   server.setExecutor(null); // creates a default executor
   server.start();
}

这是HomeHandler

class HomeHandler implements HttpHandler {
    public void handle(HttpExchange t) throws IOException {
    String filepath = "C:\\Public\\home.html";
        String response = getPage(filepath);
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes());
        os.close();
    }
}

最后是功能getPage()

private static String getPage(String page){
    String toret = "";
    BufferedReader br = null;
    try {
        String sCurrentLine;
        br = new BufferedReader(new FileReader(page));
        while ((sCurrentLine = br.readLine()) != null) {
            toret += sCurrentLine;
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null) br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return toret;
}

但是当我的主页加载时,它里面有一个图像,所以浏览器向我的服务器发出另一个图像请求,我为图像做了一个类似的处理程序,它做同样的事情,即调用函数 getPage() 传入参数图像的文件路径...

但是当它实际在浏览器中运行时,它不会显示图像。但是当我在新标签中单独打开图像时,它正确地告诉了图像的大小(谷歌浏览器是我的浏览器,截至今天最新的浏览器)..

4

2 回答 2

1

以下是如何实现一个将图像发回 UI 的处理程序:

private void forwardImage(HttpExchange exchange, String imagefilename) throws IOException {

    byte[] result = readSmallBinaryFile(imagefilename);

    if (result == null) {       
        // resource_not_found_error
    }


    exchange.getResponseHeaders().set("Content-Type", CONTENT_TYPE_IMG);
    OutputStream os = null;
    try {
        exchange.sendResponseHeaders(200, message.length);
        os = exchange.getResponseBody();
        os.write(message);
    } finally {
        os.close();
    }

    return os;
}  
于 2013-12-17T15:34:57.467 回答
1

图像是二进制数据,不能通过String(不能存储/产生特定的字节序列)。所以有byte[]直接使用。Nice 将设置响应类型Content-Type: application/jpegorpnggif

顺便说一句,您的代码正在使用您平台的编码。对于指定的编码,比如说通用 Unicode:

getBytes() // Platform dependant
getBytes("UTF-8") // Specified

new FileReader(file) // Platform dependant
new InputStreamReader(new FileInputStream(file),) // Platform dependant
new InputStreamReader(new FileInputStream(file), "UTF-8") // Specified


new FileWriter(file) // Platform dependant
new OutputStreamWriter(new FileOutputStream(file)) // Platform dependant
new OutputStreamWriter(new FileOutputStream(file), "UTF-8") // Specified

byte[] bytes;
new String(bytes) // Platform dependant
new String(bytes, "UTF-8") // Specified
于 2013-04-19T10:30:43.207 回答