gpt4 book ai didi

java - 从 HttpExchange 获取 POST 数据

转载 作者:行者123 更新时间:2023-12-05 04:10:50 30 4
gpt4 key购买 nike

这似乎是一个如此常见的用例,应该有一个简单的解决方案,但我看到的每一处都充满了极其臃肿的例子。

假设我有一个如下所示的表单:

<form action="http://localhost/endpoint" method="POST" enctype="multipart/form-data">
<input type="text" name="value" />
<input type="submit" value="Submit"/>
</form>

我提交它并在服务器上想要获取输入值:

在服务器上,我设置了一个具有单个端点的 HttpServer,在这种情况下,它直接发送正文数据:

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

import java.io.*;
import java.net.InetSocketAddress;
import java.util.function.Consumer;

public class Main {
public static void main(String[] args) {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(80), 10);
server.setExecutor(null);
server.createContext(
"/endpoint",
(HttpExchange httpExchange) -> {

InputStream input = httpExchange.getRequestBody();
StringBuilder stringBuilder = new StringBuilder();

new BufferedReader(new InputStreamReader(input))
.lines()
.forEach( (String s) -> stringBuilder.append(s + "\n") );

httpExchange.sendResponseHeaders(200, stringBuilder.length());

OutputStream output = httpExchange.getResponseBody();
output.write(stringBuilder.toString().getBytes());

httpExchange.close();
}
);

server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
}

现在,如果提交带有输入 "hi" 的表单,返回

------WebKitFormBoundaryVs2BrJjCaLCWNF9o
Content-Disposition: form-data; name="value"

hi
------WebKitFormBoundaryVs2BrJjCaLCWNF9o--

这告诉我应该有一种获取字符串值的方法,但我能看到的唯一方法是手动解析它。

(另外,我想弄点脏话,只使用 JDK 附带的库来实现这个服务器。我在工作中经常使用 Apache 服务器,但这不是我想要的试图在这里做。)

最佳答案

public Server() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/", new HttpHandler() {
@Override
public void handle(HttpExchange t) throws IOException {
StringBuilder sb = new StringBuilder();
InputStream ios = t.getRequestBody();
int i;
while ((i = ios.read()) != -1) {
sb.append((char) i);
}
System.out.println("hm: " + sb.toString());

String response = " <html>\n"
+ "<body>\n"
+ "\n"
+ "<form action=\"http://localhost:8000\" method=\"post\">\n"
+ "input: <input type=\"text\" name=\"input\"><br>\n"
+ "input2: <input type=\"text\" name=\"input2\"><br>\n"
+ "<input type=\"submit\">\n"
+ "</form>\n"
+ "\n"
+ "</body>\n"
+ "</html> ";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();

}
});
server.setExecutor(null);
server.start();
}

不确定你是想要这个还是什么,但这会返回所有帖子页面的字符串,其中包含名称和值

那样

input=value&input2=value2&......

关于java - 从 HttpExchange 获取 POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43822262/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com