gpt4 book ai didi

java.io.IOException : Server returned HTTP response code: 405 for URL 异常

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:02:52 24 4
gpt4 key购买 nike

我有一个在线 servlet,我正在尝试联系它以进行一些基本测试。这是 servlet 代码:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class index extends HttpServlet {
private static final long serialVersionUID = 1L;

public index() {
super();
}

protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
long time1 = System.currentTimeMillis();
long time2 = time1 + 10000;
out.println(time1);
long i = 400000000l;
while (System.currentTimeMillis() < time2) {
i++;
}
out.print(time2);
}
}

现在,我尝试使用以下代码从服务器获取信息:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpRequest {
public static void main(String args[]) {
BufferedReader rd;
OutputStreamWriter wr;

try {
URL url = new URL("http://blahblahblah/index");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();

conn.setConnectTimeout(50000);
rd = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
System.out.println(e.toString());
}

}
}

但是我一直收到相同的 405 错误。我做错了什么?

最佳答案

您看到的是 HttpServletdoPost() 的默认实现,因为您没有在 override索引 servlet。

protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if (protocol.endsWith("1.1")) {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, msg);
} else {
resp.sendError(HttpServletResponse.SC_BAD_REQUEST, msg);
}
}

立即发送 405 响应。

这是因为你打电话

conn.getOutputStream()

这使得 URLConnection 认为您默认发送的是 POST,而不是您期望的 GET。您甚至都没有使用 OutputStream 那么为什么要打开它,然后 flush() 然后再不使用它呢?

wr = new OutputStreamWriter(conn.getOutputStream());
wr.flush();

关于java.io.IOException : Server returned HTTP response code: 405 for URL 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18687122/

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