---
title: Encoding attributes
description: The writeToken method of the Agent class takes a java.util.Map collection of attributes and encodes them into an OpenToken, which is then written to the HTTP response.
component: java
page_id: java:setup:pf_java_ik_encoding_attributes
canonical_url: https://docs.pingidentity.com/integrations/java/setup/pf_java_ik_encoding_attributes.html
revdate: June 21, 2024
section_ids:
  sample-code: Sample code
---

# Encoding attributes

The `writeToken` method of the Agent class takes a `java.util.Map` collection of attributes and encodes them into an OpenToken, which is then written to the HTTP response.

|   |                                                                                             |
| - | ------------------------------------------------------------------------------------------- |
|   | To generate a valid token, the collection of attributes must contain a key named `subject`. |

If any errors are encountered while creating the token or writing the token out to the response, a `TokenException` is thrown.

The following example code shows how to use the writeToken method:

|   |                                                                                                                                                                                   |
| - | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|   | This code is the same for both the Java native and Apache commons multimap methods described in [Reading and writing OpenTokens](pf_java_ik_reading_and_writing_opentokens.html). |

## Sample code

```
String username = (String)request.getSession().getAttribute("username");
Map<String, String> userInfo = new HashMap<String, String>();
userInfo.put(Agent.TOKEN_SUBJECT, username);
String returnUrl = "https://<PingFederate-DNS>:9031" + request.getParameter("resume");
. . . .
try {
   UrlHelper urlHelper = new UrlHelper(returnUrl);
   //See the "Reading and writing OpenTokens" topic for sample code
   //that instantiates and configures an Agent instance
   agent.writeToken(userInfo,response,urlHelper,false);
   returnUrl = (String)urlHelper.toString();
}
catch(TokenException e) {
// Handle exception
}
```
