【问题标题】:Java HttpURLConnection issue: Server redirected too many timesJava HttpURLConnection 问题:服务器重定向太多次
【发布时间】:2017-04-19 17:16:39
【问题描述】:

我正在使用 Java 1.7。

当我在 Firefox 中使用 Postman 测试请求时,我得到一个响应状态:200,并且 Json 响应良好。

当我用我的 Java 应用程序测试它时,我得到了这个异常:

java.net.ProtocolException: 服务器重定向次数过多 (20)

这是我的java代码:

try{
    String charset = "UTF-8";
    URL url = new URL("http://example.com/ws");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET"); 
    con.setRequestProperty("Accept-Charset", charset);
    con.setRequestProperty("token", "mytokenvalue");
    int responseCode = con.getResponseCode();
    BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    System.out.println(response.toString());
}catch(Exception ex){
    ex.printStackTrace();
}

在这一行抛出异常:

int responseCode = con.getResponseCode();

【问题讨论】:

  • 那么为什么您的服务器会发送超过 20 个重定向?你知道吗?尝试使用一些 http 嗅探器来查看它发回的内容。
  • 看起来像一个重定向循环。你的服务器路由配置是什么?
  • 您是否使用任何类型的身份验证?如果是这样,也许你会发现这篇文章很有用:stackoverflow.com/questions/11022934/…
  • 谢谢马可,好电话!

标签: java


【解决方案1】:

您必须在打开连接之前设置此属性:

HttpURLConnection.setFollowRedirects(false);

【讨论】:

    猜你喜欢
    • 2018-11-22
    • 2013-09-21
    • 2023-03-25
    • 2015-02-16
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2012-11-20
    相关资源
    最近更新 更多