简体   繁体   English

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

[英]Send file in response from Java HTTP server

I'm using Ember for front-end and Java for back-end. 我在前端使用Ember,在后端使用Java。 On typing localhost:8080, I need to show the Ember homepage index.html. 在键入localhost:8080时,我需要显示Ember主页index.html。 Previously, I used Node.js and the below line did the trick 以前,我使用Node.js,下面的代码可以解决问题

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

Now on shifting to Java, I'm unable to achieve the same result. 现在转向Java,我无法达到相同的结果。 I tried the below code. 我尝试了以下代码。

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();
    } 
}

But, unfortunately I'm getting the below error on trying to load the home page. 但是,不幸的是,在尝试加载主页时出现以下错误。

"Uncaught SyntaxError: Unexpected token <" “未捕获的SyntaxError:意外的令牌<”

The same Ember application when processed using Node.js works fine. 使用Node.js处理时,相同的Ember应用程序可以正常工作。 I guess I'm not sending the HTTP response properly. 我想我没有正确发送HTTP响应。 Any help is appreciated. 任何帮助表示赞赏。

Maybe you have an issue with the path of your file. 也许您的文件路径有问题。 Also notice that the readFileToString is deprecated. 另请注意,不建议使用readFileToString

Here is a working server that will send your index.html to your frontend. 这是一个正常工作的服务器,它将把您的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();
        }
    }
}

You can use the lightweight server nanoHttpd . 您可以使用轻量级服务器nanoHttpd With the following code you can send your index.html file to your frontend also. 使用以下代码,您也可以将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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM