【问题标题】:HTTP connection made in Java fails with too many redirects?用 Java 建立的 HTTP 连接因重定向过多而失败?
【发布时间】:2017-04-11 15:14:48
【问题描述】:

我有一个简单的基于 Tomcat 的 Java 应用程序,它起到某种防火墙的作用——我从“外部”接收请求,将它们重新路由到“内部”的资源,然后将结果返回到“外部”。 "

这适用于 GET,但我正在尝试为不同的请求添加 POST 函数,但无法使其正常工作。 “内部”远程服务器受密码保护,我无法让远程服务器接受身份验证凭据(它们适用于 GET,因此凭据很好。)相反,Tomcat 服务器一遍又一遍地调用 Authenticator,最终失败。这是我得到的错误:

    java.net.ProtocolException: Server redirected too many  times (20)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1848)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
        at com.mystuff.house.server.MyServlet.doPost(MyServlet.java:191)

我确定我在做一些愚蠢的事情,但我看不到它在哪里。这是 servlet doPost() 例程的主要内容:

        URL url = new URL("HTTP", "10.10.1.101", -1, "/myresource");
        URLConnection con = url.openConnection();
        HttpURLConnection http = (HttpURLConnection) con;
        http.setRequestMethod("POST");
        http.setDoOutput(true);
        String encoded = String.valueOf(Base64.getEncoder().encode((a.getUsername().concat(":").concat(a.getPassword())).getBytes()));
        http.setRequestProperty("Authorization", "Basic "+encoded);
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        // Read the POST payload from the front end post, write to back end post
        InputStream r = request.getInputStream();
        OutputStream os = http.getOutputStream();
        int j = 0;
        while ((j = r.read()) != -1) {
            os.write((byte) j);
        }

        http.connect();

        // Try reading the result from the back end, push it back to the front end
        try {
            InputStream i = http.getInputStream();
            OutputStream o = response.getOutputStream();

            // read/write bytes until EOF
            j = 0;
            while ((j = i.read()) != -1) {
                o.write((byte) j);
            }
        } catch (Exception ex) {
            System.out.println("AIEEEE!  Error receiving page from HTTP call");
            ex.printStackTrace();
        }

【问题讨论】:

  • 这是服务器端的问题,不是这个客户端代码的问题,除非授权有问题。
  • @EJP 原来是身份验证问题。我点击的特定 URL 需要不同的密码。远程服务器从未发回 401 或 403,这是我所期望的。如果您想发表您的评论作为答案,我很乐意将其标记为正确。

标签: java tomcat servlets


【解决方案1】:

这个问题,经过一番调查,原来是身份验证对我试图在远程服务器上点击的特定 URL 无效。

我曾预计会从远程服务器返回 403、401 或 407,但这从未发生过,而是发生了这种“重定向”。因此,如果您尝试从 Java 代码中访问受密码保护的 URL,则需要注意这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多