001package com.box.sdk; 002 003import java.io.IOException; 004import java.io.InputStreamReader; 005import java.net.HttpURLConnection; 006 007/** 008 * Used to read HTTP responses containing JSON from the Box API. 009 * 010 * <p>This request type extends BoxAPIResponse to provide additional functionality for handling JSON strings. It reads 011 * the response body into a string and allows the JSON in the response to be logged.</p> 012 */ 013public class BoxJSONResponse extends BoxAPIResponse { 014 private static final int BUFFER_SIZE = 8192; 015 016 private String json; 017 018 /** 019 * Constructs a BoxJSONResponse using an HttpURLConnection. 020 * @param connection a connection that has already sent a request to the API. 021 */ 022 public BoxJSONResponse(HttpURLConnection connection) { 023 super(connection); 024 } 025 026 /** 027 * Gets the body of the response as a JSON string. When this method is called, the response's body will be read and 028 * the response will be disconnected, meaning that the stream returned by {@link #getBody} can no longer be used. 029 * @return the body of the response as a JSON string. 030 */ 031 public String getJSON() { 032 if (this.json != null) { 033 return this.json; 034 } 035 036 InputStreamReader reader = new InputStreamReader(this.getBody(), StandardCharsets.UTF_8); 037 StringBuilder builder = new StringBuilder(); 038 char[] buffer = new char[BUFFER_SIZE]; 039 040 try { 041 int read = reader.read(buffer, 0, BUFFER_SIZE); 042 while (read != -1) { 043 builder.append(buffer, 0, read); 044 read = reader.read(buffer, 0, BUFFER_SIZE); 045 } 046 047 this.disconnect(); 048 reader.close(); 049 } catch (IOException e) { 050 throw new BoxAPIException("Couldn't connect to the Box API due to a network error.", e); 051 } 052 this.json = builder.toString(); 053 return this.json; 054 } 055 056 @Override 057 protected String bodyToString() { 058 String bodyString = super.bodyToString(); 059 if (bodyString == null) { 060 return this.getJSON(); 061 } else { 062 return bodyString; 063 } 064 } 065}