@@ -61,6 +61,43 @@ protected void onStarted() {
61
61
// Package / Private Methods
62
62
///////////////////////////////////////////////////////////////////////////
63
63
64
+ /**
65
+ * Opens an http/s connection and handles redirects that switch protocols.
66
+ */
67
+ InputStream connect (URL url , int redirects ) throws Exception {
68
+ HttpURLConnection conn = (HttpURLConnection ) url .openConnection ();
69
+ conn .setDoInput (true );
70
+ conn .setDoOutput (true );
71
+ conn .setInstanceFollowRedirects (true );
72
+ conn .setUseCaches (false );
73
+ conn .setRequestMethod ("POST" );
74
+ conn .setRequestProperty ("Content-Type" , "application/json" );
75
+ //write the request map
76
+ writeConnectionRequest (conn );
77
+ //read response
78
+ int rc = conn .getResponseCode ();
79
+ debug (debug () ? "Connection initialization response code " + rc : null );
80
+ if ((rc >= 300 ) && (rc <= 307 ) && (rc != 306 ) &&
81
+ (rc != HttpURLConnection .HTTP_NOT_MODIFIED )) {
82
+ conn .disconnect ();
83
+ if (++redirects > 5 ) {
84
+ throw new IllegalStateException ("Too many redirects" );
85
+ }
86
+ String location = conn .getHeaderField ("Location" );
87
+ if (location == null ) {
88
+ throw new IllegalStateException ("Redirect missing location header" );
89
+ }
90
+ url = new URL (url , location );
91
+ debug (debug () ? "Following redirect to " + url : null );
92
+ return connect (url , redirects );
93
+ }
94
+ if ((rc < 200 ) || (rc >= 300 )) {
95
+ conn .disconnect ();
96
+ throwConnectionException (conn , rc );
97
+ }
98
+ return conn .getInputStream ();
99
+ }
100
+
64
101
DSLink getLink () {
65
102
return connection .getLink ();
66
103
}
@@ -81,24 +118,9 @@ DSMap getResponse() {
81
118
void initializeConnection () throws Exception {
82
119
String uri = makeBrokerUrl ();
83
120
debug (debug () ? "Broker URI " + uri : null );
84
- HttpURLConnection conn = (HttpURLConnection ) new URL (uri ).openConnection ();
85
- conn .setDoInput (true );
86
- conn .setDoOutput (true );
87
- conn .setInstanceFollowRedirects (true );
88
- conn .setUseCaches (false );
89
- conn .setRequestMethod ("POST" );
90
- conn .setRequestProperty ("Content-Type" , "application/json" );
91
- //write the request map
92
- writeConnectionRequest (conn );
93
- //read response
94
- int rc = conn .getResponseCode ();
95
- debug (debug () ? "Connection initialization response code " + rc : null );
96
- if ((rc < 200 ) || (rc >= 300 )) {
97
- throwConnectionException (conn , rc );
98
- }
99
121
JsonReader in = null ;
100
122
try {
101
- in = new JsonReader (conn . getInputStream ( ), "UTF-8" );
123
+ in = new JsonReader (connect ( new URL ( uri ), 0 ), "UTF-8" );
102
124
response = in .getMap ();
103
125
put (BROKER_RES , response ).setReadOnly (true );
104
126
trace (trace () ? response : null );
0 commit comments