0

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?

MWiesner
  • 8,868
  • 11
  • 36
  • 70
Cardsfan
  • 99
  • 1
  • 1
  • 7
  • After 20 redirects, you can rest assured that the client hangs in a redirect loop. – Martin Zeitler Aug 14 '22 at 04:50
  • 2
    Maybe read the [documentation](https://www.usps.com/business/web-tools-apis/general-api-developer-guide.htm#_Toc24631959), to begin with? – Martin Zeitler Aug 14 '22 at 04:59
  • I had originally intended to use the api's in the referenced documentation, but it only provides package tracking. I had to obtain information about regular first class mail, so it seemed that the only option was to parse the informed delivery web pages. Is it possible to cleanly handle the redirect loop via cookie management, or am I just out of luck? – Cardsfan Aug 14 '22 at 17:35

0 Answers0