如何解决使用西里尔符号发送 HTTP 响应时的 Java OutputStream 问题
我有一个关于在 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 举报,一经查实,本站将立刻删除。