Getting “java.net.ProtocolException: Server redirected too many times” Error

后端 未结 4 2268
误落风尘
误落风尘 2020-12-08 19:20

I\'m making a simple URL request with code like this:

URL url = new URL(webpage);
URLConnection urlConnection = url.openConnection();
InputStream is = urlCon         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 19:59

    It's apparently redirecting in an infinite loop because you don't maintain the user session. The session is usually backed by a cookie. You need to create a CookieManager before you use URLConnection.

    // First set the default cookie manager.
    CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
    
    // All the following subsequent URLConnections will use the same cookie manager.
    URLConnection connection = new URL(url).openConnection();
    // ...
    
    connection = new URL(url).openConnection();
    // ...
    
    connection = new URL(url).openConnection();
    // ...
    

    See also:

    • Using java.net.URLConnection to fire and handle HTTP requests

提交回复
热议问题