原生java写一个简答的http服务 并且能够接受get请求指定的参数 并且还响应json格式的数据给浏览器 请用代码写出来
以下是一个简单的原生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(8080), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // 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 = parseQuery(query);
String response = createJSONResponse(params);
t.getResponseHeaders().add("Content-Type", "application/json");
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
private Map<String, String> parseQuery(String query) {
Map<String, String> result = new HashMap<>();
if (query != null) {
String[] pairs = query.split("&");
for (String pair : pairs) {
String[] parts = pair.split("=");
if (parts.length == 2) {
result.put(parts[0], parts[1]);
}
}
}
return result;
}
private String createJSONResponse(Map<String, String> params) {
JSONObject json = new JSONObject();
for (Map.Entry<String, String> entry : params.entrySet()) {
json.put(entry.getKey(), entry.getValue());
}
return json.toString();
}
}
}
这个HTTP服务监听8080端口,当收到请求时,会解析请求参数,然后根据参数生成JSON格式的响应数据。例如,如果请求URL为http://localhost:8080/?name=John&age=30,则响应数据为{"name":"John","age":"30"}。
原文地址: https://www.cveoy.top/t/topic/bIC8 著作权归作者所有。请勿转载和采集!