English 中文(简体)
来自Java HTTP服务器的端文档
原标题:Send file in response from Java HTTP server
  • 时间:2017-12-19 17:24:42
  •  标签:
  • java

Im将Ember用于前端,Java用于后端。 关于打字当地东道方:8080,我需要显示Ember主页指数.html。 此前,我使用了Node.js,以下一线是trick。

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

But, unfortunately I m getting the below error on trying to load the home page.

“未预见到”

在使用Node.js进行处理时,同样的Ember申请也进行了罚款。 我猜测,I m没有向吉大港山区提供适当的反应。 感谢任何帮助。

问题回答

也许你会问你档案的道路。 并请注意,<代码>现成附件/代码>已折旧。

这里是一个工作服务器,将送至您的前端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("
Running! Point your browsers to http://localhost:8080/ 
");
    }

    public static void main(String[] args) {
        try {
            new App();
        } catch (IOException ioe) {
            System.err.println("Couldn t start server:
" + 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);
    }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签