使用西里尔符号发送 HTTP 响应时的 Java OutputStream 问题

问题描述

我有一个关于在 Java 中通过 HTTP 发送俄文文本的问题。 看起来问题与编码有关。

我有一个用 Java 实现的 HTTP 服务器:

public class Main extends Application {

@Override
public void start(Stage primaryStage) throws Exception{

    HttpServer server = HttpServer.create(new InetSocketAddress("localhost",8001),0);
    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);
    server.createContext("/",new  MyHttpHandler());
    server.setExecutor(threadPoolExecutor);
    server.start();
   System.out.println(" Server started on port 8001");

}


public static void main(String[] args) {
    launch(args);
}

}

还有 MyHttpHandler

class MyHttpHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) throws IOException {

        String requestParamValue = null;

        if("GET".equals(httpExchange.getRequestMethod()) && httpExchange.getRequestURI().toString().equals("/get-first")) {
            requestParamValue = handleGetRequest(httpExchange);
        }
        System.out.println("Message to the client sent successfully");
    }
    private String handleGetRequest(HttpExchange httpExchange) throws IOException {
        String s = "Hello!";
        httpExchange.sendResponseHeaders(200,s.length());
        OutputStream os = httpExchange.getResponseBody();
        os.write(s.getBytes());
        os.close();
        return "OK";
    }

当我启动服务器并打开浏览器并输入搜索行:http://localhost:8001/get-first 时,我收到消息:Hello!

但是!一旦我更改 s = "Привет!" 或将其更改为包含任何俄语符号,我根本没有得到任何答案,并且在调试我的程序时会在 os.write(s.getBytes())

处停止

我使用了一些这样的手动编码方法

String myString = "some cyrillic text";
byte bytes[] = myString.getBytes("ISO-8859-1"); 
String value = new String(bytes,"UTF-8");

但不幸的是它没有成功。 请帮我解决这个问题!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)