How to resolve: Server redirected too many times?

423 views Asked by At

Looked through stackoverflow for resolutions, and found this but that didn't help.

Getting this exception

java.net.ProtocolException: Server redirected too many  times (20)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1932)
    at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1520)
    at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:250)
    at GetMailStatus.main(GetMailStatus.java:27)

for this block of code that's trying to access an InformedDelivery url with credentials

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.Base64;


public class GetMailStatus {

    public static void main(String[] args) {

        try {
            URL url = new URL ("https://informeddelivery.usps.com/.........");
            String encoding = Base64.getEncoder().encodeToString(("xxxx:yyyy").getBytes("UTF-8"));
            CookieManager msCookieManager = new java.net.CookieManager(null, CookiePolicy.ACCEPT_ALL);
            CookieHandler.setDefault(msCookieManager);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty  ("Authorization", "Basic " + encoding);

            InputStream content = (InputStream)connection.getInputStream();
            BufferedReader in   =
                    new BufferedReader (new InputStreamReader (content));
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

}

The code was modified based on the referenced stackoverflow discussion. I'm assuming I'm still not managing cookies correctly. Any suggestions?

0

There are 0 answers