使用java原生写一个get接口用于获取用户信息
以下是一个简单的例子,假设我们有一个User类表示用户信息:
public class User {
private String name;
private int age;
private String email;
public User(String name, int age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getEmail() {
return email;
}
}
接下来,我们可以创建一个UserController类来处理用户信息的请求:
import java.util.HashMap;
import java.util.Map;
public class UserController {
private Map<String, User> users;
public UserController() {
users = new HashMap<>();
// 添加一些示例用户
users.put("john", new User("John Smith", 32, "john@example.com"));
users.put("sarah", new User("Sarah Johnson", 28, "sarah@example.com"));
users.put("bob", new User("Bob Brown", 41, "bob@example.com"));
}
public User getUser(String username) {
return users.get(username);
}
}
这个UserController类包含一个Map用于存储用户信息,并且有一个getUser方法来根据用户名获取用户信息。
最后,我们需要创建一个简单的HTTP服务器来处理请求:
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 UserServer {
private static final int SERVER_PORT = 8000;
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(SERVER_PORT), 0);
server.createContext("/user", new UserHandler());
server.setExecutor(null); // 使用默认的executor
server.start();
System.out.println("服务器已启动,监听端口:" + SERVER_PORT);
}
static class UserHandler implements HttpHandler {
private UserController userController;
public UserHandler() {
userController = new UserController();
}
@Override
public void handle(HttpExchange exchange) throws IOException {
if ("GET".equals(exchange.getRequestMethod())) {
// 获取请求参数
String username = exchange.getRequestURI().getQuery();
if (username != null) {
// 根据用户名获取用户信息
User user = userController.getUser(username);
if (user != null) {
// 返回用户信息
String response = "Name: " + user.getName() + "\nAge: " + user.getAge() + "\nEmail: " + user.getEmail();
exchange.sendResponseHeaders(200, response.length());
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
return;
}
}
}
// 返回404 Not Found
exchange.sendResponseHeaders(404, 0);
exchange.close();
}
}
}
这个UserServer类创建了一个HTTP服务器,监听8000端口,并注册了一个/user路径的处理器。当收到GET请求时,处理器会从URI中获取用户名,并使用UserController来获取用户信息。如果找到用户,处理器会返回用户信息,否则返回404 Not Found响应。
现在,我们可以使用浏览器或curl等工具来访问http://localhost:8000/user?username=john,就可以获取John Smith的信息了。注意,这个例子并没有考虑安全性问题,实际应用中需要进行身份验证和授权等处理。
原文地址: https://www.cveoy.top/t/topic/bFSJ 著作权归作者所有。请勿转载和采集!