001package com.box.sdk; 002 003import com.box.sdk.http.HttpHeaders; 004import com.box.sdk.http.HttpMethod; 005import com.eclipsesource.json.JsonObject; 006import java.io.ByteArrayInputStream; 007import java.io.IOException; 008import java.io.InputStream; 009import java.io.OutputStream; 010import java.net.HttpURLConnection; 011import java.net.MalformedURLException; 012import java.net.ProtocolException; 013import java.net.URL; 014import java.security.KeyManagementException; 015import java.security.NoSuchAlgorithmException; 016import java.util.ArrayList; 017import java.util.List; 018import java.util.Map; 019import java.util.logging.Level; 020import java.util.logging.Logger; 021import javax.net.ssl.HttpsURLConnection; 022import javax.net.ssl.SSLContext; 023import javax.net.ssl.SSLParameters; 024import javax.net.ssl.SSLSocketFactory; 025 026 027/** 028 * Used to make HTTP requests to the Box API. 029 * 030 * <p>All requests to the REST API are sent using this class or one of its subclasses. This class wraps {@link 031 * HttpURLConnection} in order to provide a simpler interface that can automatically handle various conditions specific 032 * to Box's API. Requests will be authenticated using a {@link BoxAPIConnection} (if one is provided), so it isn't 033 * necessary to add authorization headers. Requests can also be sent more than once, unlike with HttpURLConnection. If 034 * an error occurs while sending a request, it will be automatically retried (with a back off delay) up to the maximum 035 * number of times set in the BoxAPIConnection.</p> 036 * 037 * <p>Specifying a body for a BoxAPIRequest is done differently than it is with HttpURLConnection. Instead of writing to 038 * an OutputStream, the request is provided an {@link InputStream} which will be read when the {@link #send} method is 039 * called. This makes it easy to retry requests since the stream can automatically reset and reread with each attempt. 040 * If the stream cannot be reset, then a new stream will need to be provided before each call to send. There is also a 041 * convenience method for specifying the body as a String, which simply wraps the String with an InputStream.</p> 042 */ 043public class BoxAPIRequest { 044 private static final Logger LOGGER = Logger.getLogger(BoxAPIRequest.class.getName()); 045 private static final int BUFFER_SIZE = 8192; 046 private static final int MAX_REDIRECTS = 3; 047 private static final String ERROR_CREATING_REQUEST_BODY = "Error creating request body"; 048 private static SSLSocketFactory sslSocketFactory; 049 050 static { 051 // Setup the SSL context manually to force newer TLS version on legacy Java environments 052 // This is necessary because Java 7 uses TLSv1.0 by default, but the Box API will need 053 // to deprecate this protocol in the future. To prevent clients from breaking, we must 054 // ensure that they are using TLSv1.1 or greater! 055 SSLContext sc = null; 056 try { 057 sc = SSLContext.getDefault(); 058 SSLParameters params = sc.getDefaultSSLParameters(); 059 boolean supportsNewTLS = false; 060 for (String protocol : params.getProtocols()) { 061 if (protocol.compareTo("TLSv1") > 0) { 062 supportsNewTLS = true; 063 break; 064 } 065 } 066 if (!supportsNewTLS) { 067 // Try to upgrade to a higher TLS version 068 sc = null; 069 sc = SSLContext.getInstance("TLSv1.1"); 070 sc.init(null, null, new java.security.SecureRandom()); 071 sc = SSLContext.getInstance("TLSv1.2"); 072 sc.init(null, null, new java.security.SecureRandom()); 073 } 074 } catch (NoSuchAlgorithmException ex) { 075 if (sc == null) { 076 LOGGER.warning("Unable to set up SSL context for HTTPS! This may result in the inability " 077 + " to connect to the Box API."); 078 } 079 if (sc != null && sc.getProtocol().equals("TLSv1")) { 080 // Could not find a good version of TLS 081 LOGGER.warning("Using deprecated TLSv1 protocol, which will be deprecated by the Box API! Upgrade " 082 + "to a newer version of Java as soon as possible."); 083 } 084 } catch (KeyManagementException ex) { 085 LOGGER.warning("Exception when initializing SSL Context! This may result in the inabilty to connect to " 086 + "the Box API"); 087 sc = null; 088 } 089 090 if (sc != null) { 091 sslSocketFactory = sc.getSocketFactory(); 092 } 093 094 } 095 096 private final BoxAPIConnection api; 097 private final List<RequestHeader> headers; 098 private final String method; 099 private URL url; 100 private BackoffCounter backoffCounter; 101 private int connectTimeout; 102 private int readTimeout; 103 private InputStream body; 104 private long bodyLength; 105 private Map<String, List<String>> requestProperties; 106 private int numRedirects; 107 private boolean followRedirects = true; 108 private boolean shouldAuthenticate; 109 110 /** 111 * Constructs an unauthenticated BoxAPIRequest. 112 * 113 * @param url the URL of the request. 114 * @param method the HTTP method of the request. 115 */ 116 public BoxAPIRequest(URL url, String method) { 117 this(null, url, method); 118 } 119 120 /** 121 * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection. 122 * 123 * @param api an API connection for authenticating the request. 124 * @param url the URL of the request. 125 * @param method the HTTP method of the request. 126 */ 127 public BoxAPIRequest(BoxAPIConnection api, URL url, String method) { 128 this.api = api; 129 this.url = url; 130 this.method = method; 131 this.headers = new ArrayList<RequestHeader>(); 132 if (api != null) { 133 Map<String, String> customHeaders = api.getHeaders(); 134 if (customHeaders != null) { 135 for (String header : customHeaders.keySet()) { 136 this.addHeader(header, customHeaders.get(header)); 137 } 138 } 139 this.headers.add(new RequestHeader("X-Box-UA", api.getBoxUAHeader())); 140 } 141 this.backoffCounter = new BackoffCounter(new Time()); 142 this.shouldAuthenticate = true; 143 if (api != null) { 144 this.connectTimeout = api.getConnectTimeout(); 145 this.readTimeout = api.getReadTimeout(); 146 } else { 147 this.connectTimeout = BoxGlobalSettings.getConnectTimeout(); 148 this.readTimeout = BoxGlobalSettings.getReadTimeout(); 149 } 150 151 this.addHeader("Accept-Encoding", "gzip"); 152 this.addHeader("Accept-Charset", "utf-8"); 153 154 } 155 156 /** 157 * Constructs an authenticated BoxAPIRequest using a provided BoxAPIConnection. 158 * 159 * @param api an API connection for authenticating the request. 160 * @param url the URL of the request. 161 * @param method the HTTP method of the request. 162 */ 163 public BoxAPIRequest(BoxAPIConnection api, URL url, HttpMethod method) { 164 this(api, url, method.name()); 165 } 166 167 /** 168 * Constructs an request, using URL and HttpMethod. 169 * 170 * @param url the URL of the request. 171 * @param method the HTTP method of the request. 172 */ 173 public BoxAPIRequest(URL url, HttpMethod method) { 174 this(url, method.name()); 175 } 176 177 /** 178 * @param apiException BoxAPIException thrown 179 * @return true if the request is one that should be retried, otherwise false 180 */ 181 public static boolean isRequestRetryable(BoxAPIException apiException) { 182 // Only requests that failed to send should be retried 183 return (apiException.getMessage() == ERROR_CREATING_REQUEST_BODY); 184 } 185 186 /** 187 * @param responseCode HTTP error code of the response 188 * @param apiException BoxAPIException thrown 189 * @return true if the response is one that should be retried, otherwise false 190 */ 191 public static boolean isResponseRetryable(int responseCode, BoxAPIException apiException) { 192 String response = apiException.getResponse(); 193 String message = apiException.getMessage(); 194 String errorCode = ""; 195 196 try { 197 JsonObject responseBody = JsonObject.readFrom(response); 198 if (responseBody.get("code") != null) { 199 errorCode = responseBody.get("code").toString(); 200 } 201 } catch (Exception e) { 202 } 203 204 Boolean isClockSkewError = responseCode == 400 205 && errorCode.contains("invalid_grant") 206 && message.contains("exp"); 207 208 return (isClockSkewError 209 || responseCode >= 500 210 || responseCode == 429); 211 } 212 213 private static boolean isResponseRedirect(int responseCode) { 214 return (responseCode == 301 || responseCode == 302); 215 } 216 217 /** 218 * Adds an HTTP header to this request. 219 * 220 * @param key the header key. 221 * @param value the header value. 222 */ 223 public void addHeader(String key, String value) { 224 if (key.equals("As-User")) { 225 for (int i = 0; i < this.headers.size(); i++) { 226 if (this.headers.get(i).getKey().equals("As-User")) { 227 this.headers.remove(i); 228 } 229 } 230 } 231 if (key.equals("X-Box-UA")) { 232 throw new IllegalArgumentException("Altering the X-Box-UA header is not permitted"); 233 } 234 this.headers.add(new RequestHeader(key, value)); 235 } 236 237 /** 238 * Gets the connect timeout for the request. 239 * 240 * @return the request connection timeout. 241 */ 242 public int getConnectTimeout() { 243 return this.connectTimeout; 244 } 245 246 /** 247 * Sets a Connect timeout for this request in milliseconds. 248 * 249 * @param timeout the timeout in milliseconds. 250 */ 251 public void setConnectTimeout(int timeout) { 252 this.connectTimeout = timeout; 253 } 254 255 /** 256 * Gets the read timeout for the request. 257 * 258 * @return the request's read timeout. 259 */ 260 public int getReadTimeout() { 261 return this.readTimeout; 262 } 263 264 /** 265 * Sets a read timeout for this request in milliseconds. 266 * 267 * @param timeout the timeout in milliseconds. 268 */ 269 public void setReadTimeout(int timeout) { 270 this.readTimeout = timeout; 271 } 272 273 /** 274 * Sets whether or not to follow redirects (i.e. Location header) 275 * 276 * @param followRedirects true to follow, false to not follow 277 */ 278 public void setFollowRedirects(boolean followRedirects) { 279 this.followRedirects = followRedirects; 280 } 281 282 /** 283 * Gets the stream containing contents of this request's body. 284 * 285 * <p>Note that any bytes that read from the returned stream won't be sent unless the stream is reset back to its 286 * initial position.</p> 287 * 288 * @return an InputStream containing the contents of this request's body. 289 */ 290 public InputStream getBody() { 291 return this.body; 292 } 293 294 /** 295 * Sets the request body to the contents of an InputStream. 296 * 297 * <p>The stream must support the {@link InputStream#reset} method if auto-retry is used or if the request needs to 298 * be resent. Otherwise, the body must be manually set before each call to {@link #send}.</p> 299 * 300 * @param stream an InputStream containing the contents of the body. 301 */ 302 public void setBody(InputStream stream) { 303 this.body = stream; 304 } 305 306 /** 307 * Sets the request body to the contents of a String. 308 * 309 * <p>If the contents of the body are large, then it may be more efficient to use an {@link InputStream} instead of 310 * a String. Using a String requires that the entire body be in memory before sending the request.</p> 311 * 312 * @param body a String containing the contents of the body. 313 */ 314 public void setBody(String body) { 315 byte[] bytes = body.getBytes(StandardCharsets.UTF_8); 316 this.bodyLength = bytes.length; 317 this.body = new ByteArrayInputStream(bytes); 318 } 319 320 /** 321 * Sets the request body to the contents of an InputStream. 322 * 323 * <p>Providing the length of the InputStream allows for the progress of the request to be monitored when calling 324 * {@link #send(ProgressListener)}.</p> 325 * 326 * <p> See {@link #setBody(InputStream)} for more information on setting the body of the request.</p> 327 * 328 * @param stream an InputStream containing the contents of the body. 329 * @param length the expected length of the stream. 330 */ 331 public void setBody(InputStream stream, long length) { 332 this.bodyLength = length; 333 this.body = stream; 334 } 335 336 /** 337 * Gets the URL from the request. 338 * 339 * @return a URL containing the URL of the request. 340 */ 341 public URL getUrl() { 342 return this.url; 343 } 344 345 /** 346 * Gets the http method from the request. 347 * 348 * @return http method 349 */ 350 public String getMethod() { 351 return this.method; 352 } 353 354 /** 355 * Get headers as list of RequestHeader objects. 356 * 357 * @return headers as list of RequestHeader objects 358 */ 359 protected List<RequestHeader> getHeaders() { 360 return this.headers; 361 } 362 363 /** 364 * Sends this request and returns a BoxAPIResponse containing the server's response. 365 * 366 * <p>The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it 367 * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response, 368 * then it can be cast to a {@link BoxJSONResponse} like so:</p> 369 * 370 * <pre>BoxJSONResponse response = (BoxJSONResponse) request.sendWithoutRetry();</pre> 371 * 372 * @return a {@link BoxAPIResponse} containing the server's response. 373 * @throws BoxAPIException if the server returns an error code or if a network error occurs. 374 */ 375 public BoxAPIResponse sendWithoutRetry() { 376 return this.trySend(null); 377 } 378 379 /** 380 * Sends this request and returns a BoxAPIResponse containing the server's response. 381 * 382 * <p>The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it 383 * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response, 384 * then it can be cast to a {@link BoxJSONResponse} like so:</p> 385 * 386 * <pre>BoxJSONResponse response = (BoxJSONResponse) request.send();</pre> 387 * 388 * <p>If the server returns an error code or if a network error occurs, then the request will be automatically 389 * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException} 390 * will be thrown.</p> 391 * 392 * <p> See {@link #send} for more information on sending requests.</p> 393 * 394 * @return a {@link BoxAPIResponse} containing the server's response. 395 * @throws BoxAPIException if the server returns an error code or if a network error occurs. 396 */ 397 public BoxAPIResponse send() { 398 return this.send(null); 399 } 400 401 /** 402 * Sends this request while monitoring its progress and returns a BoxAPIResponse containing the server's response. 403 * 404 * <p>The type of the returned BoxAPIResponse will be based on the content type returned by the server, allowing it 405 * to be cast to a more specific type. For example, if it's known that the API call will return a JSON response, 406 * then it can be cast to a {@link BoxJSONResponse} like so:</p> 407 * 408 * <p>If the server returns an error code or if a network error occurs, then the request will be automatically 409 * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException} 410 * will be thrown.</p> 411 * 412 * <p>A ProgressListener is generally only useful when the size of the request is known beforehand. If the size is 413 * unknown, then the ProgressListener will be updated for each byte sent, but the total number of bytes will be 414 * reported as 0.</p> 415 * 416 * <p> See {@link #send} for more information on sending requests.</p> 417 * 418 * @param listener a listener for monitoring the progress of the request. 419 * @return a {@link BoxAPIResponse} containing the server's response. 420 * @throws BoxAPIException if the server returns an error code or if a network error occurs. 421 */ 422 public BoxAPIResponse send(ProgressListener listener) { 423 if (this.api == null) { 424 this.backoffCounter.reset(BoxGlobalSettings.getMaxRetryAttempts() + 1); 425 } else { 426 this.backoffCounter.reset(this.api.getMaxRetryAttempts() + 1); 427 } 428 429 while (this.backoffCounter.getAttemptsRemaining() > 0) { 430 try { 431 return this.trySend(listener); 432 } catch (BoxAPIException apiException) { 433 if (!this.backoffCounter.decrement() 434 || (!isRequestRetryable(apiException) 435 && !isResponseRetryable(apiException.getResponseCode(), apiException))) { 436 throw apiException; 437 } 438 439 LOGGER.log(Level.WARNING, "Retrying request due to transient error status={0} body={1}", 440 new Object[]{apiException.getResponseCode(), apiException.getResponse()}); 441 442 try { 443 this.resetBody(); 444 } catch (IOException ioException) { 445 throw apiException; 446 } 447 448 try { 449 List<String> retryAfterHeader = apiException.getHeaders().get("Retry-After"); 450 if (retryAfterHeader == null) { 451 this.backoffCounter.waitBackoff(); 452 } else { 453 int retryAfterDelay = Integer.parseInt(retryAfterHeader.get(0)); 454 this.backoffCounter.waitBackoff(retryAfterDelay); 455 } 456 } catch (InterruptedException interruptedException) { 457 Thread.currentThread().interrupt(); 458 throw apiException; 459 } 460 } 461 } 462 463 throw new RuntimeException(); 464 } 465 466 /** 467 * Sends a request to upload a file part and returns a BoxFileUploadSessionPart containing information 468 * about the upload part. This method is separate from send() because it has custom retry logic. 469 * 470 * <p>If the server returns an error code or if a network error occurs, then the request will be automatically 471 * retried. If the maximum number of retries is reached and an error still occurs, then a {@link BoxAPIException} 472 * will be thrown.</p> 473 * 474 * @param session The BoxFileUploadSession uploading the part 475 * @param offset Offset of the part being uploaded 476 * @return A {@link BoxFileUploadSessionPart} part that has been uploaded. 477 * @throws BoxAPIException if the server returns an error code or if a network error occurs. 478 */ 479 BoxFileUploadSessionPart sendForUploadPart(BoxFileUploadSession session, long offset) { 480 if (this.api == null) { 481 this.backoffCounter.reset(BoxGlobalSettings.getMaxRetryAttempts() + 1); 482 } else { 483 this.backoffCounter.reset(this.api.getMaxRetryAttempts() + 1); 484 } 485 486 while (this.backoffCounter.getAttemptsRemaining() > 0) { 487 try { 488 BoxJSONResponse response = (BoxJSONResponse) this.trySend(null); 489 JsonObject jsonObject = JsonObject.readFrom(response.getJSON()); 490 return new BoxFileUploadSessionPart((JsonObject) jsonObject.get("part")); 491 } catch (BoxAPIException apiException) { 492 if (!this.backoffCounter.decrement() 493 || (!isRequestRetryable(apiException) 494 && !isResponseRetryable(apiException.getResponseCode(), apiException))) { 495 throw apiException; 496 } 497 if (apiException.getResponseCode() == 500) { 498 try { 499 Iterable<BoxFileUploadSessionPart> parts = session.listParts(); 500 for (BoxFileUploadSessionPart part : parts) { 501 if (part.getOffset() == offset) { 502 return part; 503 } 504 } 505 } catch (BoxAPIException e) { 506 } 507 } 508 LOGGER.log(Level.WARNING, "Retrying request due to transient error status={0} body={1}", 509 new Object[]{apiException.getResponseCode(), apiException.getResponse()}); 510 511 try { 512 this.resetBody(); 513 } catch (IOException ioException) { 514 throw apiException; 515 } 516 517 try { 518 this.backoffCounter.waitBackoff(); 519 } catch (InterruptedException interruptedException) { 520 Thread.currentThread().interrupt(); 521 throw apiException; 522 } 523 } 524 } 525 526 throw new RuntimeException(); 527 } 528 529 /** 530 * Returns a String containing the URL, HTTP method, headers and body of this request. 531 * 532 * @return a String containing information about this request. 533 */ 534 @Override 535 public String toString() { 536 String lineSeparator = System.getProperty("line.separator"); 537 StringBuilder builder = new StringBuilder(); 538 builder.append("Request"); 539 builder.append(lineSeparator); 540 builder.append(this.method); 541 builder.append(' '); 542 builder.append(this.url.toString()); 543 builder.append(lineSeparator); 544 545 if (this.requestProperties != null) { 546 547 for (Map.Entry<String, List<String>> entry : this.requestProperties.entrySet()) { 548 List<String> nonEmptyValues = new ArrayList<String>(); 549 for (String value : entry.getValue()) { 550 if (value != null && value.trim().length() != 0) { 551 nonEmptyValues.add(value); 552 } 553 } 554 555 if (nonEmptyValues.size() == 0) { 556 continue; 557 } 558 559 builder.append(entry.getKey()); 560 builder.append(": "); 561 for (String value : nonEmptyValues) { 562 builder.append(value); 563 builder.append(", "); 564 } 565 566 builder.delete(builder.length() - 2, builder.length()); 567 builder.append(lineSeparator); 568 } 569 } 570 571 String bodyString = this.bodyToString(); 572 if (bodyString != null) { 573 builder.append(lineSeparator); 574 builder.append(bodyString); 575 } 576 577 return builder.toString().trim(); 578 } 579 580 /** 581 * Returns a String representation of this request's body used in {@link #toString}. This method returns 582 * null by default. 583 * 584 * <p>A subclass may want override this method if the body can be converted to a String for logging or debugging 585 * purposes.</p> 586 * 587 * @return a String representation of this request's body. 588 */ 589 protected String bodyToString() { 590 return null; 591 } 592 593 /** 594 * Writes the body of this request to an HttpURLConnection. 595 * 596 * <p>Subclasses overriding this method must remember to close the connection's OutputStream after writing.</p> 597 * 598 * @param connection the connection to which the body should be written. 599 * @param listener an optional listener for monitoring the write progress. 600 * @throws BoxAPIException if an error occurs while writing to the connection. 601 */ 602 protected void writeBody(HttpURLConnection connection, ProgressListener listener) { 603 if (this.body == null) { 604 return; 605 } 606 607 connection.setDoOutput(true); 608 try { 609 OutputStream output = connection.getOutputStream(); 610 if (listener != null) { 611 output = new ProgressOutputStream(output, listener, this.bodyLength); 612 } 613 int b = this.body.read(); 614 while (b != -1) { 615 output.write(b); 616 b = this.body.read(); 617 } 618 output.close(); 619 } catch (IOException e) { 620 throw new BoxAPIException(ERROR_CREATING_REQUEST_BODY, e); 621 } 622 } 623 624 /** 625 * Resets the InputStream containing this request's body. 626 * 627 * <p>This method will be called before each attempt to resend the request, giving subclasses an opportunity to 628 * reset any streams that need to be read when sending the body.</p> 629 * 630 * @throws IOException if the stream cannot be reset. 631 */ 632 protected void resetBody() throws IOException { 633 if (this.body != null) { 634 this.body.reset(); 635 } 636 } 637 638 void setBackoffCounter(BackoffCounter counter) { 639 this.backoffCounter = counter; 640 } 641 642 private BoxAPIResponse trySend(ProgressListener listener) { 643 if (this.api != null) { 644 RequestInterceptor interceptor = this.api.getRequestInterceptor(); 645 if (interceptor != null) { 646 BoxAPIResponse response = interceptor.onRequest(this); 647 if (response != null) { 648 return response; 649 } 650 } 651 } 652 653 HttpURLConnection connection = this.createConnection(); 654 655 if (connection instanceof HttpsURLConnection) { 656 HttpsURLConnection httpsConnection = (HttpsURLConnection) connection; 657 658 if (sslSocketFactory != null) { 659 httpsConnection.setSSLSocketFactory(sslSocketFactory); 660 } 661 } 662 663 if (this.bodyLength > 0) { 664 connection.setFixedLengthStreamingMode((int) this.bodyLength); 665 connection.setDoOutput(true); 666 } 667 668 if (this.api != null) { 669 if (this.shouldAuthenticate) { 670 connection.addRequestProperty(HttpHeaders.AUTHORIZATION, "Bearer " + this.api.lockAccessToken()); 671 } 672 connection.setRequestProperty("User-Agent", this.api.getUserAgent()); 673 if (this.api.getProxy() != null) { 674 if (this.api.getProxyUsername() != null && this.api.getProxyPassword() != null) { 675 String usernameAndPassword = this.api.getProxyUsername() + ":" + this.api.getProxyPassword(); 676 String encoded = new String(Base64.encode(usernameAndPassword.getBytes())); 677 connection.addRequestProperty("Proxy-Authorization", "Basic " + encoded); 678 } 679 } 680 681 if (this.api instanceof SharedLinkAPIConnection) { 682 SharedLinkAPIConnection sharedItemAPI = (SharedLinkAPIConnection) this.api; 683 String sharedLink = sharedItemAPI.getSharedLink(); 684 String boxAPIValue = "shared_link=" + sharedLink; 685 String sharedLinkPassword = sharedItemAPI.getSharedLinkPassword(); 686 if (sharedLinkPassword != null) { 687 boxAPIValue += "&shared_link_password=" + sharedLinkPassword; 688 } 689 connection.addRequestProperty("BoxApi", boxAPIValue); 690 } 691 } 692 693 this.requestProperties = connection.getRequestProperties(); 694 695 int responseCode; 696 try { 697 this.writeBody(connection, listener); 698 699 // Ensure that we're connected in case writeBody() didn't write anything. 700 try { 701 connection.connect(); 702 } catch (IOException e) { 703 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 704 } 705 706 this.logRequest(connection); 707 708 // We need to manually handle redirects by creating a new HttpURLConnection so that connection pooling 709 // happens correctly. There seems to be a bug in Oracle's Java implementation where automatically handled 710 // redirects will not keep the connection alive. 711 try { 712 responseCode = connection.getResponseCode(); 713 } catch (IOException e) { 714 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 715 } 716 } finally { 717 if (this.api != null && this.shouldAuthenticate) { 718 this.api.unlockAccessToken(); 719 } 720 } 721 722 if (isResponseRedirect(responseCode)) { 723 return this.handleRedirect(connection, listener); 724 } 725 726 String contentType = connection.getContentType(); 727 BoxAPIResponse response; 728 if (contentType == null) { 729 response = new BoxAPIResponse(connection); 730 } else if (contentType.contains("application/json")) { 731 response = new BoxJSONResponse(connection); 732 } else { 733 response = new BoxAPIResponse(connection); 734 } 735 736 return response; 737 } 738 739 private BoxAPIResponse handleRedirect(HttpURLConnection connection, ProgressListener listener) { 740 if (this.numRedirects >= MAX_REDIRECTS) { 741 throw new BoxAPIException("The Box API responded with too many redirects."); 742 } 743 this.numRedirects++; 744 745 // Even though the redirect response won't have a body, we need to read the InputStream so that Java will put 746 // the connection back in the connection pool. 747 try { 748 InputStream stream = connection.getInputStream(); 749 byte[] buffer = new byte[8192]; 750 int n = stream.read(buffer); 751 while (n != -1) { 752 n = stream.read(buffer); 753 } 754 stream.close(); 755 } catch (IOException e) { 756 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 757 } 758 759 String redirect = connection.getHeaderField("Location"); 760 try { 761 this.url = new URL(redirect); 762 } catch (MalformedURLException e) { 763 throw new BoxAPIException("The Box API responded with an invalid redirect.", e); 764 } 765 766 if (this.followRedirects) { 767 return this.trySend(listener); 768 } else { 769 BoxRedirectResponse redirectResponse = new BoxRedirectResponse(); 770 redirectResponse.setRedirectURL(this.url); 771 return redirectResponse; 772 } 773 } 774 775 private void logRequest(HttpURLConnection connection) { 776 if (LOGGER.isLoggable(Level.FINE)) { 777 LOGGER.log(Level.FINE, this.toString()); 778 } 779 } 780 781 private HttpURLConnection createConnection() { 782 HttpURLConnection connection = null; 783 784 try { 785 if (this.api == null || this.api.getProxy() == null) { 786 connection = (HttpURLConnection) this.url.openConnection(); 787 } else { 788 connection = (HttpURLConnection) this.url.openConnection(this.api.getProxy()); 789 } 790 } catch (IOException e) { 791 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 792 } 793 794 try { 795 connection.setRequestMethod(this.method); 796 } catch (ProtocolException e) { 797 throw new BoxAPIException("Couldn't connect to the Box API because the request's method was invalid.", e); 798 } 799 800 connection.setConnectTimeout(this.connectTimeout); 801 connection.setReadTimeout(this.readTimeout); 802 803 // Don't allow HttpURLConnection to automatically redirect because it messes up the connection pool. See the 804 // trySend(ProgressListener) method for how we handle redirects. 805 connection.setInstanceFollowRedirects(false); 806 807 for (RequestHeader header : this.headers) { 808 connection.addRequestProperty(header.getKey(), header.getValue()); 809 } 810 811 return connection; 812 } 813 814 void shouldAuthenticate(boolean shouldAuthenticate) { 815 this.shouldAuthenticate = shouldAuthenticate; 816 } 817 818 /** 819 * Class for mapping a request header and value. 820 */ 821 public final class RequestHeader { 822 private final String key; 823 private final String value; 824 825 /** 826 * Construct a request header from header key and value. 827 * 828 * @param key header name 829 * @param value header value 830 */ 831 public RequestHeader(String key, String value) { 832 this.key = key; 833 this.value = value; 834 } 835 836 /** 837 * Get header key. 838 * 839 * @return http header name 840 */ 841 public String getKey() { 842 return this.key; 843 } 844 845 /** 846 * Get header value. 847 * 848 * @return http header value 849 */ 850 public String getValue() { 851 return this.value; 852 } 853 } 854}