001package com.box.sdk;
002
003import java.net.URL;
004
005import com.box.sdk.http.HttpMethod;
006import com.eclipsesource.json.JsonObject;
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 JsonObject jsonObject;
016
017    /**
018     * Constructs an authenticated BoxJSONRequest using a provided BoxAPIConnection.
019     * @param  api    an API connection for authenticating the request.
020     * @param  url    the URL of the request.
021     * @param  method the HTTP method of the request.
022     */
023    public BoxJSONRequest(BoxAPIConnection api, URL url, String method) {
024        super(api, url, method);
025        this.addHeader("Content-Type", "application/json");
026    }
027
028    /**
029     * Constructs an authenticated BoxJSONRequest using a provided BoxAPIConnection.
030     * @param  api    an API connection for authenticating the request.
031     * @param  url    the URL of the request.
032     * @param  method the HTTP method of the request.
033     */
034    public BoxJSONRequest(BoxAPIConnection api, URL url, HttpMethod method) {
035        super(api, url, method);
036        this.addHeader("Content-Type", "application/json");
037    }
038
039    /**
040     * Constructs an authenticated BoxJSONRequest.
041     * @param  url    the URL of the request.
042     * @param  method the HTTP method of the request.
043     */
044    public BoxJSONRequest(URL url, HttpMethod method) {
045        super(url, method);
046        this.addHeader("Content-Type", "application/json");
047    }
048
049    /**
050     * Sets the body of this request to a given JSON string.
051     * @param body the JSON string to use as the body.
052     */
053    @Override
054    public void setBody(String body) {
055        super.setBody(body);
056        this.jsonObject = JsonObject.readFrom(body);
057    }
058
059    /**
060     * Sets the body of this request to a given JsonObject.
061     * @param body the JsonObject to use as the body.
062     */
063    public void setBody(JsonObject body) {
064        super.setBody(body.toString());
065        this.jsonObject = body;
066    }
067
068    /**
069     * Gets the body of this request as a JsonObject.
070     * @return body represented as JsonObject.
071     */
072    public JsonObject getBodyAsJsonObject() {
073        return this.jsonObject;
074    }
075
076    @Override
077    protected String bodyToString() {
078        return this.jsonObject.toString();
079    }
080}