gpt4 book ai didi

Java httpserver 在收到 POST 请求时崩溃

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:21:01 25 4
gpt4 key购买 nike

我正在尝试用 Java 编写一个可以处理 POST 请求的简单 HTTP 服务器。当我的服务器成功接收到 GET 时,它在 POST 时崩溃了。

这是服务器

public class RequestHandler {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/requests", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}

static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "hello world";
t.sendResponseHeaders(200, response.length());
System.out.println(response);
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}

这是我用来发送 POST 的 Java 代码

// HTTP POST request
private void sendPost() throws Exception {

String url = "http://localhost:8080/requests";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();

int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();

//print result
System.out.println(response.toString());
}

每次 POST 请求在这一行崩溃

HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

但是当我将 URL 更改为示例中提供的 URL 时,我发现它有效。

最佳答案

代替

HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

使用

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

您正在连接到一个非 HTTPS 的 URL。当您调用 obj.openConnection() 时,它会决定连接是 HTTP 还是 HTTPS,并返回适当的对象。当它是 http 时,它不会返回 HttpsURLConnection,因此您无法转换为它。

但是,由于 HttpsURLconnection 扩展了 HttpURLConnection,因此使用 HttpURLConnection 将适用于 httphttps 网址。您在代码中调用的方法都存在于 HttpURLConnection 类中。

关于Java httpserver 在收到 POST 请求时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28325241/

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