001package com.box.sdk; 002 003import com.box.sdk.http.HttpMethod; 004import com.eclipsesource.json.Json; 005import com.eclipsesource.json.JsonObject; 006import com.eclipsesource.json.JsonValue; 007import java.net.URL; 008 009/** 010 * Used to make HTTP requests containing JSON to the Box API. 011 * 012 * <p>This request type extends BoxAPIRequest to provide additional functionality for handling JSON strings. It 013 * automatically sets the appropriate "Content-Type" HTTP headers and allows the JSON in the request to be logged.</p> 014 */ 015public class BoxJSONRequest extends BoxAPIRequest { 016 private JsonValue jsonValue; 017 018 /** 019 * Constructs an authenticated BoxJSONRequest using a provided BoxAPIConnection. 020 * 021 * @param api an API connection for authenticating the request. 022 * @param url the URL of the request. 023 * @param method the HTTP method of the request. 024 */ 025 public BoxJSONRequest(BoxAPIConnection api, URL url, String method) { 026 super(api, url, method); 027 this.addHeader("Content-Type", "application/json"); 028 } 029 030 /** 031 * Constructs an authenticated BoxJSONRequest using a provided BoxAPIConnection. 032 * 033 * @param api an API connection for authenticating the request. 034 * @param url the URL of the request. 035 * @param method the HTTP method of the request. 036 */ 037 public BoxJSONRequest(BoxAPIConnection api, URL url, HttpMethod method) { 038 super(api, url, method); 039 this.addHeader("Content-Type", "application/json"); 040 } 041 042 /** 043 * Constructs an authenticated BoxJSONRequest. 044 * 045 * @param url the URL of the request. 046 * @param method the HTTP method of the request. 047 */ 048 public BoxJSONRequest(URL url, HttpMethod method) { 049 super(url, method); 050 this.addHeader("Content-Type", "application/json"); 051 } 052 053 /** 054 * Sets the body of this request to a given JSON string. 055 * 056 * @param body the JSON string to use as the body. 057 */ 058 @Override 059 public void setBody(String body) { 060 super.setBody(body); 061 this.jsonValue = Json.parse(body); 062 } 063 064 /** 065 * Sets the body of this request to a given JsonObject. 066 * 067 * @param body the JsonObject to use as the body. 068 */ 069 public void setBody(JsonObject body) { 070 super.setBody(body.toString()); 071 this.jsonValue = body; 072 } 073 074 /** 075 * Gets the body of this request as a JsonObject. 076 * 077 * @return body represented as JsonObject. 078 */ 079 public JsonObject getBodyAsJsonObject() { 080 if (this.jsonValue.isObject()) { 081 return this.jsonValue.asObject(); 082 } 083 084 return null; 085 } 086 087 /** 088 * Gets the body of this request as a {@link JsonValue}. 089 * 090 * @return body represented as JsonValue 091 */ 092 public JsonValue getBodyAsJsonValue() { 093 return this.jsonValue; 094 } 095 096 @Override 097 protected String bodyToString() { 098 return this.jsonValue != null ? this.jsonValue.toString() : null; 099 } 100}