以下是一个简单的原生Java HTTP服务,它可以接受GET请求中指定的参数,并响应JSON格式的数据给浏览器:

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

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

import org.json.JSONObject;

public class SimpleHttpServer {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/hello", 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 query = t.getRequestURI().getQuery();
            Map<String, String> params = queryToMap(query);

            JSONObject response = new JSONObject();
            response.put("message", "Hello " + params.get("name"));

            t.getResponseHeaders().set("Content-Type", "application/json");
            t.sendResponseHeaders(200, response.toString().length());

            OutputStream os = t.getResponseBody();
            os.write(response.toString().getBytes());
            os.close();
        }
    }

    public static Map<String, String> queryToMap(String query) {
        Map<String, String> result = new HashMap<>();
        for (String param : query.split("&")) {
            String[] entry = param.split("=");
            if (entry.length > 1) {
                result.put(entry[0], entry[1]);
            } else {
                result.put(entry[0], "");
            }
        }
        return result;
    }
}

在这个例子中,我们创建了一个HTTP服务器,监听在8000端口上,并创建了一个处理程序来处理来自“/hello”路径的请求。在处理程序中,我们首先从请求URI中提取查询参数,并将它们转换为一个Map对象。然后,我们使用这些参数来构造一个JSON响应,其中包含一条问候消息。最后,我们设置响应头的Content-Type为“application/json”,并将JSON响应发送回浏览器。

要测试这个HTTP服务器,只需在浏览器中访问http://localhost:8000/hello?name=World,其中“name”是一个查询参数,它的值为“World”。服务器应该会返回一个JSON响应,其中包含一条问候消息,如下所示:

{"message":"Hello World"}
原生java写一个http服务 并且能够接受get请求指定的参数 并且还响应json格式的数据给浏览器 必须使用HttpServletRequest类库来接收get参数 并且必须使用java内置的包来响应json格式的数据 请用代码写出来

原文地址: https://www.cveoy.top/t/topic/bIGY 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录