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