001package com.box.sdk; 002 003import java.net.URL; 004 005import com.box.sdk.http.HttpMethod; 006import com.eclipsesource.json.JsonObject; 007import com.eclipsesource.json.JsonValue; 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 * @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 * @param api an API connection for authenticating the request. 032 * @param url the URL of the request. 033 * @param method the HTTP method of the request. 034 */ 035 public BoxJSONRequest(BoxAPIConnection api, URL url, HttpMethod method) { 036 super(api, url, method); 037 this.addHeader("Content-Type", "application/json"); 038 } 039 040 /** 041 * Constructs an authenticated BoxJSONRequest. 042 * @param url the URL of the request. 043 * @param method the HTTP method of the request. 044 */ 045 public BoxJSONRequest(URL url, HttpMethod method) { 046 super(url, method); 047 this.addHeader("Content-Type", "application/json"); 048 } 049 050 /** 051 * Sets the body of this request to a given JSON string. 052 * @param body the JSON string to use as the body. 053 */ 054 @Override 055 public void setBody(String body) { 056 super.setBody(body); 057 this.jsonValue = JsonValue.readFrom(body); 058 } 059 060 /** 061 * Sets the body of this request to a given JsonObject. 062 * @param body the JsonObject to use as the body. 063 */ 064 public void setBody(JsonObject body) { 065 super.setBody(body.toString()); 066 this.jsonValue = body; 067 } 068 069 /** 070 * Gets the body of this request as a JsonObject. 071 * @return body represented as JsonObject. 072 */ 073 public JsonObject getBodyAsJsonObject() { 074 if (this.jsonValue.isObject()) { 075 return this.jsonValue.asObject(); 076 } 077 078 return null; 079 } 080 081 /** 082 * Gets the body of this request as a {@link JsonValue}. 083 * @return body represented as JsonValue 084 */ 085 public JsonValue getBodyAsJsonValue() { 086 return this.jsonValue; 087 } 088 089 @Override 090 protected String bodyToString() { 091 return this.jsonValue.toString(); 092 } 093}