Search code examples
javarestlet

ClientResource null attributes


I have an issue with ClientResource. When I initialize, the attributes are null.

String url = "..."
ClientResource clientResource = new ClientResource(url);

clientResource.getRequestAttributes() produces null.

This produces a problem for me to add custom headers to my call.

Btw, there is a reason that clientResource.getHeaders is not present at ClientResource API? I'm working with Restlet version 2.3.1 here is my pom:

<repositories>
  <repository>
    <id>maven-restlet</id>
    <name>Public online Restlet repository</name>
    <url>http://maven.restlet.org</url>
  </repository>
</repositories>

<dependencies>
  <dependency>
    <groupId>org.restlet.jse</groupId>
    <artifactId>org.restlet.ext.json</artifactId>
    <version>${restlet.version}</version>
  </dependency>
</dependencies>

Solution

  • You can simply use the following code to add a custom header:

    ClientResource cr = new ClientResource("http://...");
    cr.getRequest().getHeaders().add("MyCustomHeader", "some value");
    

    Edit

    If the getHeaders method doesn't exist for the version of Restlet you use, replace it by the following code:

    Series<Header> headers = (Series<Header>) cr.getAttributes().get(
                HeaderConstants.ATTRIBUTE_HEADERS);
    if (headers == null) {
        headers = new Series<Header>(Header.class);
        cr.getAttributes().put(HeaderConstants.ATTRIBUTE_HEADERS, headers);
    }
    
    headers.add("MyCustomHeader", "some value");