Java中的简单HTTP服务器,仅使用Java SE API [英] simple HTTP server in Java using only Java SE API

查看:126
本文介绍了Java中的简单HTTP服务器,仅使用Java SE API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法只使用Java SE API在Java中创建一个非常基本的HTTP服务器(仅支持GET / POST),而无需编写代码来手动解析HTTP请求并手动格式化HTTP响应? Java SE API很好地封装了HttpURLConnection中的HTTP客户端功能,但是有一个用于HTTP服务器功能的模拟吗?

Is there a way to create a very basic HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to manually parse HTTP requests and manually format HTTP responses? The Java SE API nicely encapsulates the HTTP client functionality in HttpURLConnection, but is there an analog for HTTP server functionality?

为了清楚起见,我遇到了很多问题我在网上看到的ServerSocket示例是他们自己做请求解析/响应格式化和错误处理,这是繁琐,容易出错,并且不太可能是全面的,我试图避免它出于这些原因。

Just to be clear, the problem I have with a lot of ServerSocket examples I've seen online is that they do their own request parsing/response formatting and error handling, which is tedious, error-prone, and not likely to be comprehensive, and I'm trying to avoid it for those reasons.

作为我试图避免的手动HTTP操作的一个例子:

As an example of the manual HTTP manipulation that I'm trying to avoid:

http://java.sun.com/developer/technicalArticles/Networking/Webserver/WebServercode.html

推荐答案

从Java SE 6开始, Sun Oracle JRE中有一个内置的HTTP服务器。 com.sun.net.httpserver 包摘要概述了所涉及的类并包含示例。

Since Java SE 6, there's a builtin HTTP server in Sun Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.

这是一个从他们的文档中复制的启动示例,你可以在Java 6 +上复制'n'paste'n'run。

Here's a kickoff example copypasted from their docs, you can just copy'n'paste'n'run it on Java 6+.


package com.stackoverflow.q3732109;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class Test {

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

    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}


注意到它们的示例中的 response.length()部分是坏的,应该是 response.getBytes( )。长度。即使这样, getBytes()方法也必须显式指定您在响应头中指定的字符集。唉,尽管对初学者有误导,但它毕竟只是一个基本的启动示例。

Noted should be that the response.length() part in their example is bad, it should have been response.getBytes().length. Even then, the getBytes() method must explicitly specify the charset which you then specify in the response header. Alas, albeit misguiding to starters, it's after all just a basic kickoff example.

执行它然后转到 http:// localhost:8000 / test 你会看到以下回复:

Execute it and go to http://localhost:8000/test and you'll see the following response:


这是回复

This is the response






关于使用 com。太阳。* 类,请注意,这与一些开发人员的想法相反,绝对不会被众所周知的FAQ 为什么开发人员不应该编写调用'sun'软件包的程序。该FAQ涉及Oracle JRE内部使用的 sun。* 包(例如 sun.misc.BASE64Encoder ) (当你在不同的JRE上运行它时会因你的应用程序而被杀掉),而不是 com.sun。* 包。 Sun / Oracle也只是在Java SE API之上开发软件,就像Apache等所有其他公司一样。仅当涉及某个Java API的实现(例如GlassFish)时,才禁止使用 com.sun。* 类(但不禁止)。 Java EE impl),Mojarra(JSF impl),Jersey(JAX-RS impl)等。


As to using com.sun.* classes, do note that this is, in contrary to what some developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.* package (such as sun.misc.BASE64Encoder) for internal usage by the Oracle JRE (which would thus kill your application when you run it on a different JRE), not the com.sun.* package. Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.

这篇关于Java中的简单HTTP服务器,仅使用Java SE API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆