All Downloads are FREE. Search and download functionalities are using the official Maven repository.

templates.plugins.spincast-http-client.spincast-http-client.html Maven / Gradle / Ivy

{#==========================================
Spincast Properties File Config
==========================================#}
{% extends "../../layout.html" %}

{% block sectionClasses %}plugins plugins-spincast-http-client{% endblock %}
{% block meta_title %}Plugins - Spincast HTTP Client{% endblock %}
{% block meta_description %}Builder to easily create and send HTTP requests.{% endblock %}

{% block scripts %}

{% endblock %}

{% block body %}

Overview

Provides an easy way of creating and sending HTTP requests.

It 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 {
    //...
}

Installation

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)
        // 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()));
        // other modules...
    }
    
    // ...
}

Usage

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,
                             IHttpClient httpClient) {
        super(exchange);
        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)
    Starts a builder for a GET request.
  • IPostRequestBuilder POST(String url)
    Starts a builder for a POST request.
  • IPutRequestBuilder PUT(String url)
    Starts a builder for a PUT request.
  • IDeleteRequestBuilder DELETE(String url)
    Starts a builder for a DELETE request.
  • IOptionsRequestBuilder OPTIONS(String url)
    Starts a builder for a OPTIONS request.
  • IHeadRequestBuilder HEAD(String url)
    Starts a builder for a HEAD request.
  • ITraceRequestBuilder TRACE(String url)
    Starts a builder for a TRACE request.
  • IConnectRequestBuilder CONNECT(String url)
    Starts a builder for a CONNECT request.
  • IPatchRequestBuilder PATCH(String url)
    Starts a builder for a PATCH request.

IRequestBuilderBase's methods

The IRequestBuilderBase is the interface that all request builders implements: IGetRequestBuilder, IPostRequestBuilder, etc.

  • T addHeaderValue(String key, String value)
    Adds a value to the specified header. Existing values will be kept.
  • T addHeaderValues(String key, List<String> values)
    Adds some values to the specified header. Existing values will be kept.
  • T setHeaders(Map<String, List<String>> headers)
    Sets the headers. Existing headers will be overwritten.
  • T setHeaderValues(String key, List<String> values)
    Sets the values of the specified header. Existing values of this header will be overwritten.
  • T addCookie(String name, String value)
    Adds a cookie.
  • T addCookie(ICookie cookie)
    Adds a cookie.
  • T addCookies(Collection<ICookie> cookies)
    Adds some cookies.
  • T setRequestConfig(RequestConfig requestConfig)
    Sets a custom RequestConfig to use. If not provided, a default one will be used.
  • T setHttpClientBuilder(HttpClientBuilder httpClientBuilder)
    Sets a specific HttpClientBuilder to use. If not provided, a default one will be used.
  • T disableSslCertificateErrors()
    Disables 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.
  • IHttpResponse send()
    Sends the request and gets the response.

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)
    Sets the Form datas entity.
    A form data can contain more than one value.
    Overwrites any existing Form datas.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - Custom HttpEntity
    When you set or add an entity of a new type, the existing entity is overwritten.
  • T setEntityFormData(String name, List<String> values)
    Sets a Form data entity.
    A form data can contain more than one value.
    Overwrites the existing Form data of the same name, but keeps the other ones.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - Custom HttpEntity
    When you set or add an entity of a new type, the existing entity is overwritten.
  • T addEntityFormDataValue(String name, String value)
    Adds a value to a Form data.
    Keeps the existing values.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - Custom HttpEntity
    When you set or add an entity of a new type, the existing entity is overwritten.
  • T setEntityString(String entity, String contentType)
    Sets a String entity.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - Custom HttpEntity
    When you set or add an entity of a new type, the existing entity is overwritten.
  • T setEntity(HttpEntity entity)
    Sets an custom HttpEntity entity to be sent.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - custom HttpEntity
    When you set or add an entity of a new type, the existing entity is overwritten.
  • T setEntityJson(Object object)
    Sets a Json entity to be sent.
    The object will be converted to a Json's
    String representation and sent using the application/json
    Content-Type.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - Custom HttpEntity
    When you set or add an entity of a new type, the existing entity is overwritten.
  • T setEntityXml(Object object)
    Sets a XML entity to be sent.
    The object will be converted to a XML and sent using the application/xml
    Content-Type.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - Custom HttpEntity
    When you set or add an entity of a new type, the existing entity is overwritten.
  • T addEntityFileUpload(String path, String name)
    Adds a file to upload. More than one file can be uploaded at one time. The specified file is added to the existing ones.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - Custom HttpEntity
    @param path the path to the file to upload, on the file system
    @param name the name to use for the uploaded file.
  • T addEntityFileUpload(String path, boolean isClasspathPath, String name)
    Adds a file to upload. More than one file can be uploaded at one time. The specified file is added to the existing ones.
    Only one type of entity can be set amongs:
    - Form datas entity
    - String entity
    - File upload
    - Custom HttpEntity
    @param path the path to the file to upload
    @param isClasspathPath if true, the path to the file to upload is on the classpath, otherwise, it's on the file system.
    @param name the name to use for the uploaded file.

IHttpResponse's methods

The IHttpResponse is the response you receive when you send a request.

  • int getStatus()
    Gets the HTTP status.
  • String getContentType()
    Gets the Content-Type.
  • Map<String, List<String>> getHeaders()
    Gets the headers.
  • List<String> getHeader(String name)
    Gets an header. An header can have more than one value.
  • String getHeaderFirst(String name)
    Gets the first value of an header.
  • Map<String, ICookie> getCookies()
    Gets the cookies.
  • ICookie getCookie(String name)
    Gets a cookie.
  • boolean isGzipped()
    Is the response gzipped?
  • String getContentAsString()
    Gets the content as a UTF-8 String.
  • String getContentAsString(String encoding)
    Gets the content as a String using the specified encoding.
  • byte[] getContentAsByteArray()
    Get the content as byte[].

{% endblock %}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy