用Java HTTP服务器发送文件响应

4

我正在使用Ember作为前端和Java作为后端。当输入localhost:8080时,需要显示Ember主页index.html。以前,我使用Node.js,并且下面的代码行起到了作用

res.sendfile('./public/index.html');

现在我正在转向Java,但是我无法达到相同的结果。我尝试了以下代码。

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

static class HHandler implements HttpHandler 
{
    @Override
    public void handle(HttpExchange t) throws IOException 
    {
        File file = new File("..\\public\\index.html");
        String response = FileUtils.readFileToString(file);
        String encoding = "UTF-8";
        t.getResponseHeaders().set("Content-Type", "text/html; charset=" + encoding);
        t.getResponseHeaders().set("Accept-Ranges", "bytes");
        t.sendResponseHeaders(200, response.length());
        OutputStream os = t.getResponseBody();
        os.write(response.getBytes("UTF-8"));
        os.close();
    } 
}

但是,不幸的是在尝试加载主页时我收到了以下错误信息。

"未捕获的 SyntaxError: 意外的令牌 <"

当使用 Node.js 处理相同的 Ember 应用程序时正常工作。我猜测我没有正确地发送 HTTP 响应。任何帮助将不胜感激。


os.close()之前尝试使用os.flush(),看看是否有所不同。 - undefined
2个回答

0
也许你的文件路径有问题。还要注意,readFileToString 方法已经过时了。
下面是一个可用的服务器,它会将你的 index.html 发送给前端。
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

public class myServer {
    public static void main(String[] args) throws Exception {
        System.out.println("server ...");
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/", new HHandler());
        //server.createContext("/getbookarray", new HHandler());
        //server.setExecutor(null); // creates a default executor
        server.start();
        //server.getExecutor();
    }

    static class HHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            Headers h = t.getResponseHeaders();



            String line;
            String resp = "";

            try {
                File newFile = new File("src/index.html");
                System.out.println("*****lecture du fichier*****");
                System.out.println("nom du fichier: " + newFile.getName());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(newFile)));

                while ((line = bufferedReader.readLine()) != null) {
                    System.out.println(line);
                    resp += line;
                }
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            h.add("Content-Type", "application/json");
            t.sendResponseHeaders(200, resp.length());
            OutputStream os = t.getResponseBody();
            os.write(resp.getBytes());
            os.close();
        }
    }
}

你可以使用轻量级的服务器 nanoHttpd。通过以下代码,你可以将你的 index.html 文件发送给你的前端。
import fi.iki.elonen.NanoHTTPD;

import java.io.*;

public class App extends NanoHTTPD {

    public App() throws IOException {
        super(8080);
        start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        System.out.println("\nRunning! Point your browsers to http://localhost:8080/ \n");
    }

    public static void main(String[] args) {
        try {
            new App();
        } catch (IOException ioe) {
            System.err.println("Couldn't start server:\n" + ioe);
        }
    }

    @Override
    public Response serve(NanoHTTPD.IHTTPSession session) {

        File newFile = new File("src/index.html");
        System.out.println("*****lecture du fichier*****");
        System.out.println("nom du fichier: " + newFile.getName());


        String line;
        String reponse = "";

        try {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(newFile)));
            while ((line = bufferedReader.readLine()) != null){
                reponse += line;
            }
            bufferedReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newFixedLengthResponse(reponse);
    }
}

嘿,edkeveked,我尝试了你的建议。但我仍然得到相同的错误。还有其他建议吗? - undefined
谢谢 @edkeveked。我今晚会测试一下,并告诉你结果如何。 - undefined
好的,@GiridharanJ,请告诉我! - undefined

0
尝试将文件以二进制信息(字节序列)而不是文本形式读取。因为最终你还是要将从文件中读取的字符串转换为字节。你可以使用Files.readAllBytes(Path path)来读取文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接