{#========================================== Spincast HTTP Client plugin ==========================================#} {% extends "../../layout.html" %} {% block sectionClasses %}plugins plugins-spincast-http-client{% endblock %} {% block meta_title %}Plugins - Spincast HTTP Client{% endblock %} {% block meta_description %}Client to easily create and send HTTP requests.{% endblock %} {% block scripts %} {% endblock %} {% block body %}
Provides an easy way of creating and sending HTTP requests.
Please note that this is the light version of the Spincast HTTP client,
without support for WebSockets. If you want your HTTP client to be able
to establish WebSocket connections, use the
Spincast HTTP Client With WebSocket version!
This client is built around
Apache HttpClient. Note that
no extra dependencies are added by this plugin because it uses the
shaded version of Apache HttpClient, which is already included in the spincast-core
artifact.
Usage example:
IHttpResponse response = httpClient.GET("https://www.google.com").send();
System.out.println(response.getContentAsString());
Or:
IUser user = getUser();
IHttpResponse response = httpClient.POST("https://example.com/api/users")
.setEntityJson(user)
.addCookie("cookieKey", "cookieValue")
.addHeaderValue("headerKey", "headerValue")
.send();
if(response.getStatus() == 200) { // or use: HttpStatus.SC_OK
String content = response.getContentAsString();
ICookie cookie = response.getCookie("someCookie");
String header = response.getHeaderFirst("someHeader");
} else {
//...
}
The Spincast Http Client is already available in the test Maven scope,
when you include the spincast-testing-default
or the spincast-testing-core artifacts to help you with your tests.
If you want to use the Spincast Http Client in your application, and not only in your tests,
you have to include it as a regular dependency:
<dependency>
<groupId>org.spincast</groupId>
<artifactId>spincast-plugins-http-client</artifactId>
<version>{{spincastCurrrentVersion}}</version>
</dependency>
Then, install the plugin's Guice module, by passing it to the Guice.createInjector(...) method:
Injector guice = Guice.createInjector(
new AppModule(args),
new SpincastHttpClientPluginGuiceModule(IAppRequestContext.class,
IAppWebsocketContext.class)
// other modules...
);
... or by using the install(...) method from your custom Guice module:
public class AppModule extends SpincastDefaultGuiceModule {
//...
@Override
protected void configure() {
super.configure();
install(new SpincastHttpClientPluginGuiceModule(getRequestContextType(),
getWebsocketContextType()));
// other modules...
}
// ...
}
To use Spincast's HTTP Client, you can inject IHttpClient where you need it.
For example:
public class AppController {
private final IHttpClient httpClient;
@Inject
public AppController(IHttpClient httpClient) {
this.httpClient = httpClient;
}
protected IHttpClient httpClient() {
return this.httpClient;
}
public void myRouteHandler(IAppRequestContext context) {
IHttpResponse response = httpClient().GET("https://www.google.com").send();
if(response.getStatus() == HttpStatus.SC_OK) {
//...
}
}
}
You can also extend your custom request context objects to add
IHttpClient as an add-on. To do that, let's tweak some components:
Your IAppRequestContext interface
public interface IAppRequestContext extends IRequestContext<IAppRequestContext> {
//...
public IHttpClient httpClient();
}
The request content implementation
public class AppRequestContext extends RequestContextBase<IAppRequestContext>
implements IAppRequestContext {
private final IHttpClient httpClient;
@AssistedInject
public AppRequestContext(@Assisted Object exchange,
RequestContextBaseDeps<IAppRequestContext> requestContextBaseDeps,
IHttpClient httpClient) {
super(exchange, requestContextBaseDeps);
this.httpClient = httpClient;
}
//...
@Override
public IHttpClient httpClient() {
return this.httpClient;
}
}
Then, you can use the HTTP Client from your route handlers:
public class AppController {
public void myRouteHandler(IAppRequestContext context) {
IHttpResponse response = context.httpClient().GET("https://www.google.com").send();
if(response.getStatus() == HttpStatus.SC_OK) {
//...
}
}
}
IHttpClient's methods
IGetRequestBuilder GET(String url)
GET request.
IPostRequestBuilder POST(String url)
POST request.
IPutRequestBuilder PUT(String url)
PUT request.
IDeleteRequestBuilder DELETE(String url)
DELETE request.
IOptionsRequestBuilder OPTIONS(String url)
OPTIONS request.
IHeadRequestBuilder HEAD(String url)
HEAD request.
ITraceRequestBuilder TRACE(String url)
TRACE request.
IConnectRequestBuilder CONNECT(String url)
CONNECT request.
IPatchRequestBuilder PATCH(String url)
PATCH request.
IHttpRequestBuilder's methods
The IHttpRequestBuilder is the interface that all request builders
implements:
IGetRequestBuilder, IPostRequestBuilder, etc.
T addHeaderValue(String key, String value)
T addHeaderValues(String key, List<String> values)
T setHeaders(Map<String, List<String>> headers)
T setHeaderValues(String key, List<String> values)
T addJsonAcceptHeader()
Accept head for Json.
T addXMLAcceptHeader()
Accept head for XML.
T addHTMLAcceptHeader()
Accept head for HTML.
T addPlainTextAcceptHeader()
Accept head for plain text.
T addCookie(String name, String value)
T addCookie(ICookie cookie)
T addCookies(Collection<ICookie> cookies)
T setRequestConfig(RequestConfig requestConfig)
RequestConfig to use. If not provided,
a default one will be used.
T setHttpClientBuilder(HttpClientBuilder httpClientBuilder)
HttpClientBuilder to use. If not provided,
a default one will be used.
T disableSslCertificateErrors()
SSL certificates errors (such as self-signed
certificate errors).
SSL certificate errors are not disabled by default.
Be sure you know what you are doing if you disable this! It may lead to
some security concerns.
T setHttpAuthCredentials(String username, String password)
IHttpResponse send()
IEntitySenderRequestBuilderBase's methods
The IEntitySenderRequestBuilderBase is the interface implemented by
builders which can send an entity with the request, or that can upload files:
IPostRequestBuilder, IPutRequestBuilder and
IPatchRequestBuilder.
T setEntityFormDatas(Map<String, List<String>> params)
HttpEntity
T setEntityFormData(String name, List<String> values)
HttpEntity
T addEntityFormDataValue(String name, String value)
HttpEntity
T setEntityString(String entity, String contentType)
HttpEntity
T setEntity(HttpEntity entity)
HttpEntity entity to be sent.
HttpEntity
T setEntityJson(Object object)
Json entity to be sent.
Json's
application/json
HttpEntity
T setEntityXml(Object object)
XML entity to be sent.
XML
and sent using the application/xml
HttpEntity
T addEntityFileUpload(String path, String name)
HttpEntity
T addEntityFileUpload(String path, boolean isClasspathPath, String name)
HttpEntity
IHttpResponse's methods
The IHttpResponse is the response you receive when you send
a request.
int getStatus()
String getContentType()
Map<String, List<String>> getHeaders()
List<String> getHeader(String name)
String getHeaderFirst(String name)
Map<String, ICookie> getCookies()
ICookie getCookie(String name)
boolean isGzipped()
String getContentAsString()
UTF-8 String.
String getContentAsString(String encoding)
byte[] getContentAsByteArray()
byte[].