@@ -47,6 +47,7 @@ public class BoxAPIRequest {
4747 private static final int MAX_REDIRECTS = 3 ;
4848 private static final String ERROR_CREATING_REQUEST_BODY = "Error creating request body" ;
4949 private static final int BUFFER_SIZE = 8192 ;
50+ private static final EmptyBody EMPTY_BODY = new EmptyBody ();
5051 private static SSLSocketFactory sslSocketFactory ;
5152
5253 static {
@@ -616,6 +617,18 @@ protected void writeBody(HttpURLConnection connection, ProgressListener listener
616617 }
617618
618619 connection .setDoOutput (true );
620+
621+ if (bodyLength > 0 ) {
622+ connection .setFixedLengthStreamingMode ((int ) this .bodyLength );
623+ }
624+
625+ // if method requires body, but it is empty we do not write anything.
626+ // Just tell HTTP client to add proper Content-length header
627+ if (this .body instanceof EmptyBody ) {
628+ connection .setFixedLengthStreamingMode (0 );
629+ return ;
630+ }
631+
619632 try {
620633 OutputStream output = connection .getOutputStream ();
621634 if (listener != null ) {
@@ -676,11 +689,6 @@ private BoxAPIResponse trySend(ProgressListener listener) {
676689 }
677690 }
678691
679- if (this .bodyLength > 0 ) {
680- connection .setFixedLengthStreamingMode ((int ) this .bodyLength );
681- connection .setDoOutput (true );
682- }
683-
684692 if (this .api != null ) {
685693 if (this .shouldAuthenticate ) {
686694 connection .addRequestProperty (HttpHeaders .AUTHORIZATION , "Bearer " + this .api .lockAccessToken ());
@@ -842,6 +850,15 @@ void shouldAuthenticate(boolean shouldAuthenticate) {
842850 this .shouldAuthenticate = shouldAuthenticate ;
843851 }
844852
853+ /**
854+ * Use it to force sending empty body with HTTP methods that require body to be sent.
855+ * This will force HTTP client to add proper Content-length header.
856+ */
857+ void noBody () {
858+ this .bodyLength = 0 ;
859+ this .body = EMPTY_BODY ;
860+ }
861+
845862 /**
846863 * Class for mapping a request header and value.
847864 */
@@ -878,4 +895,12 @@ public String getValue() {
878895 return this .value ;
879896 }
880897 }
898+
899+ private static final class EmptyBody extends InputStream {
900+
901+ @ Override
902+ public int read () throws IOException {
903+ return 0 ;
904+ }
905+ }
881906}
0 commit comments