java.io.IOException:服务器返回 HTTP 响应代码:URL 405

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18687122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:10:35  来源:igfitidea点击:

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

javaiosservlets

提问by spacitron

I have a servlet online that I'm trying to contact in order to do some basic testing. This is the servlet code:

我有一个在线 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);
    }
}

Now, I'm trying to get information from the server using the following code:

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

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());
               }

     }
}

However I keep getting the same 405 error. What am I doing wrong?

但是我不断收到相同的 405 错误。我究竟做错了什么?

采纳答案by Sotirios Delimanolis

What you are seeing is the HttpServlet's default implementation of doPost(), since you don't overrideit in your indexservlet.

您所看到的是HttpServlet的默认实现doPost(),因为您overrideindexservlet 中没有它。

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);
    }
}

which immediately sends a 405 response.

它立即发送 405 响应。

This occurs because you call

发生这种情况是因为您调用

conn.getOutputStream()

which makes the URLConnectionthink you are sending a POSTby default, not the GETyou are expecting. You aren't even using the OutputStreamso why open it, then flush()it and never us it again?

这使URLConnection您认为您POST默认发送的是一个,而不是GET您所期望的。你甚至不使用,OutputStream为什么打开它,然后flush()它,然后再也不使用它?

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

回答by molabss

You can also put a check if the request method is GET or POST:

您还可以检查请求方法是 GET 还是 POST:

private static final int READ_TIMEOUT = 100000;
private static final int CONNECT_TIMEOUT = 150000;
public static final String POST = "POST";
public static final String GET = "GET";
public static final String PUT = "PUT";
public static final String DELETE = "DELETE";
public static final String HEAD = "HEAD";
private URL url = null;
private HttpURLConnection  conn = null;
private OutputStream os = null;
private BufferedWriter writer = null;
private InputStream is = null;
private int responseCode = 0;

private String request(String method, String url, List<NameValuePair> params) throws IOException {

    if(params != null && method == GET){
        url = url.concat("?");
        url = url.concat(getQuery(params));
    }

    this.url = new URL(url);
    conn = (HttpURLConnection) this.url.openConnection();
    conn.setReadTimeout(READ_TIMEOUT);
    conn.setConnectTimeout(CONNECT_TIMEOUT);
    conn.setRequestMethod(method);
    conn.setDoInput(true);
    conn.setDoOutput(true);

    if(params != null && method == POST){
        os = conn.getOutputStream();
        writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(getQuery(params));
        writer.flush();
        writer.close();
        os.close();
    }

    conn.connect();
    responseCode = conn.getResponseCode();
    is = conn.getInputStream();
    String contentAsString = getStringFromInputStream(is);
    return contentAsString;
}



private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException {
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params){

        if (first){
            first = false;
        } else {
            result.append("&");
        }
        result.append(URLEncoder.encode(pair.getName(),"UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(),"UTF-8"));
    }

    return result.toString();
}