|
16 | 16 | import java.io.UnsupportedEncodingException; |
17 | 17 | import java.lang.reflect.Field; |
18 | 18 | import java.lang.reflect.Type; |
| 19 | +import java.net.CookieHandler; |
| 20 | +import java.net.CookieManager; |
19 | 21 | import java.net.HttpURLConnection; |
20 | 22 | import java.net.URL; |
21 | 23 | import java.net.URLEncoder; |
@@ -46,6 +48,11 @@ public class JsonServiceClient implements ServiceClient { |
46 | 48 | public JsonServiceClient(String baseUrl) { |
47 | 49 | this.baseUrl = baseUrl.endsWith("/") ? baseUrl : baseUrl + "/"; |
48 | 50 | this.replyUrl = this.baseUrl + "json/reply/"; |
| 51 | + |
| 52 | + //Automatically populate response cookies |
| 53 | + if (CookieHandler.getDefault() == null){ |
| 54 | + CookieHandler.setDefault(new CookieManager()); |
| 55 | + } |
49 | 56 | } |
50 | 57 |
|
51 | 58 | public void setTimeout(int timeoutMs) { |
@@ -172,11 +179,13 @@ public HttpURLConnection createRequest(String requestUrl, String httpMethod, byt |
172 | 179 | private static void addBasicAuth(HttpURLConnection req, String userName, String password) { |
173 | 180 | req.setRequestProperty(HttpHeaders.Authorization, |
174 | 181 | "Basic " + Utils.toBase64String(userName + ":" + password)); |
| 182 | + req.setRequestProperty("X-Auth", "Basic"); // HttpURLConnection doesn't allow re-reading Authorization Header |
175 | 183 | } |
176 | 184 |
|
177 | 185 | private static boolean shouldAuthenticate(HttpURLConnection req, String userName, String password){ |
178 | 186 | try { |
179 | 187 | return req.getResponseCode() == 401 |
| 188 | + && req.getRequestProperty("X-Auth") == null //only auth if auth never attempted |
180 | 189 | && userName != null |
181 | 190 | && password != null; |
182 | 191 | } catch (IOException e) { |
@@ -364,8 +373,8 @@ public <TResponse> TResponse send(String requestUrl, String httpMethod, byte[] r |
364 | 373 | else { |
365 | 374 | BufferedReader reader = new BufferedReader(new InputStreamReader(is)); |
366 | 375 | TResponse response = resClass != null |
367 | | - ? (TResponse) getGson().fromJson(reader, resClass) |
368 | | - : (TResponse) getGson().fromJson(reader, resType); |
| 376 | + ? (TResponse) getGson().fromJson(reader, resClass) |
| 377 | + : (TResponse) getGson().fromJson(reader, resType); |
369 | 378 |
|
370 | 379 | reader.close(); |
371 | 380 | return response; |
|
0 commit comments