首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Java HttpURLConnection问题:服务器重定向次数过多

Java HttpURLConnection问题:服务器重定向次数过多
EN

Stack Overflow用户
提问于 2016-12-05 10:31:37
回答 1查看 6K关注 0票数 1

我正在使用Java1.7。

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

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

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

以下是我的java代码:

代码语言:javascript
复制
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();
}

在这一行中抛出异常:

代码语言:javascript
复制
int responseCode = con.getResponseCode();
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-03 13:21:45

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

HttpURLConnection.setFollowRedirects(false);

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40972116

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档