cz.jalasoft.net.http.HttpPostRequest Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of HttpClient Show documentation
Show all versions of HttpClient Show documentation
API for communicating over HTTP.
/*
* Copyright (c) 2015 Avast a.s., www.avast.com
*/
package cz.jalasoft.net.http;
import java.net.URI;
/**
* A request that is sent over HTTP as a POST request.
*
* @author Jan Lastovicka ([email protected])
* @since 2015-02-21
*/
public final class HttpPostRequest {
/**
* A factory method that start a process of the request
* creation.
* @param uri URI as a target server where a request will be sent.
* @return a builder, never null
* @throws java.lang.IllegalArgumentException if uri is null
*/
public static Builder to(URI uri) {
return new Builder(uri);
}
/**
* A factory method that starts a process of the request
* creation.
* @param uriBuilder a builder of URI, must not be null
* @return a builder, never null
* @throws java.lang.IllegalArgumentException if uriBuilder is null
*/
public static Builder to(URIBuilder uriBuilder) {
return new Builder(uriBuilder.build());
}
//-------------------------------------------------------------------------
//INSTANCE SCOPE
//-------------------------------------------------------------------------
private final URI uri;
private final String contentType;
private final String payload;
HttpPostRequest(Builder builder) {
this.uri = builder.uri;
this.contentType = builder.contentType;
this.payload = builder.payload;
}
/**
* Gets a URI
* @return never null
*/
public URI uri() {
return uri;
}
/**
* Gets a payload of a request.
* @return never null or empty.
*/
public byte[] getPayload() {
return payload.getBytes();
}
/**
* Gets a string representation of a payload.
* @return never null or emty.
*/
public String payloadAsString() {
return payload;
}
/**
* Gets a type of content.
* @return never null or empty.
*/
public String contentType() {
return contentType;
}
@Override
public String toString() {
return new StringBuilder("HttpPostRequest[")
.append("URI: ")
.append(uri)
.append(", ")
.append("payload: ")
.append(payload)
.append("]")
.toString();
}
//----------------------------------------------------
//BUILDER
//----------------------------------------------------
public static final class Builder {
private URI uri;
private String contentType;
private String payload;
Builder(URI uri) {
this.uri = uri;
}
public Builder withJsonPayload(String payload) {
this.payload = payload;
this.contentType = "application/json; charset=utf-8";
return this;
}
public Builder withFormParametersPayload(String params) {
this.payload = params;
this.contentType = "application/x-www-form-urlencoded";
return this;
}
public HttpPostRequest build() {
if (payload == null) {
throw new IllegalStateException("Payload not defined.");
}
return new HttpPostRequest(this);
}
}
}