原生Java编写GET接口接收参数并响应浏览器
以下是使用原生Java编写的一个GET接口,它可以接收一个参数,并将接收到的参数响应给浏览器:
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 MyHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext('/get', new MyHandler());
server.setExecutor(null);
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String query = exchange.getRequestURI().getQuery();
String response = 'Received parameter: ' + query;
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
这个代码创建了一个HTTP服务器,监听8080端口,并注册了一个GET请求处理器。当浏览器发送一个GET请求到/get路径时,处理器会从请求中获取参数,并将响应字符串发送回浏览器。例如,如果浏览器请求http://localhost:8080/get?name=John,服务器将响应Received parameter: name=John。
原文地址: https://www.cveoy.top/t/topic/m9UU 著作权归作者所有。请勿转载和采集!