@@ -495,6 +495,61 @@ private void writeCache(StringBuilder sb, String accession) throws IOException {
495495 fw .write (sb .toString ());
496496 fw .close ();
497497 }
498+
499+ /**
500+ * Open a URL connection.
501+ *
502+ * Follows redirects.
503+ * @param url
504+ * @throws IOException
505+ */
506+ private static HttpURLConnection openURLConnection (URL url ) throws IOException {
507+ // This method should be moved to a utility class in BioJava 5.0
508+
509+ final int timeout = 5000 ;
510+ final String useragent = "BioJava" ;
511+
512+ HttpURLConnection conn = (HttpURLConnection ) url .openConnection ();
513+ conn .setRequestProperty ("User-Agent" , useragent );
514+ conn .setInstanceFollowRedirects (true );
515+ conn .setConnectTimeout (timeout );
516+ conn .setReadTimeout (timeout );
517+
518+ int status = conn .getResponseCode ();
519+ while (status == HttpURLConnection .HTTP_MOVED_TEMP
520+ || status == HttpURLConnection .HTTP_MOVED_PERM
521+ || status == HttpURLConnection .HTTP_SEE_OTHER ) {
522+ // Redirect!
523+ String newUrl = conn .getHeaderField ("Location" );
524+
525+ if (newUrl .equals (url .toString ())) {
526+ throw new IOException ("Cyclic redirect detected at " +newUrl );
527+ }
528+
529+ // Preserve cookies
530+ String cookies = conn .getHeaderField ("Set-Cookie" );
531+
532+ // open the new connection again
533+ url = new URL (newUrl );
534+ conn .disconnect ();
535+ conn = (HttpURLConnection ) url .openConnection ();
536+ if (cookies != null ) {
537+ conn .setRequestProperty ("Cookie" , cookies );
538+ }
539+ conn .addRequestProperty ("User-Agent" , useragent );
540+ conn .setInstanceFollowRedirects (true );
541+ conn .setConnectTimeout (timeout );
542+ conn .setReadTimeout (timeout );
543+ conn .connect ();
544+
545+ status = conn .getResponseCode ();
546+
547+ logger .info ("Redirecting from {} to {}" , url , newUrl );
548+ }
549+ conn .connect ();
550+
551+ return conn ;
552+ }
498553
499554 private StringBuilder fetchUniprotXML (String uniprotURL )
500555 throws IOException , CompoundNotFoundException {
@@ -504,11 +559,9 @@ private StringBuilder fetchUniprotXML(String uniprotURL)
504559 int attempt = 5 ;
505560 List <String > errorCodes = new ArrayList <String >();
506561 while (attempt > 0 ) {
507- HttpURLConnection uniprotConnection = (HttpURLConnection ) uniprot .openConnection ();
508- uniprotConnection .setRequestProperty ("User-Agent" , "BioJava" );
509- uniprotConnection .connect ();
562+ HttpURLConnection uniprotConnection = openURLConnection (uniprot );
510563 int statusCode = uniprotConnection .getResponseCode ();
511- if (statusCode == 200 ) {
564+ if (statusCode == HttpURLConnection . HTTP_OK ) {
512565 BufferedReader in = new BufferedReader (
513566 new InputStreamReader (
514567 uniprotConnection .getInputStream ()));
0 commit comments