How to generate direct line token to start a new conversation between your own client application and bot framework in Java
You can enable the communication between your bot framework and your client application using Direct Line API.
When you add your client application as a site to communicate with your bot framework through azure portal, bot framework will generate secret keys. Your client application can use these generated secret keys to authenticate direct line requests issued to your bot framework.
Let me explain how we can generate token to start a conversations between your own client and bot framework.
When we send a request to direct line for generating token, if the request is successful it will send the conversation id and token that is valid to that conversation id.
If client application already has a earlier used conversation Id, you can pass that id as an input to this method for generating token. If there is no conversation id, you can pass null value. Return type of this method is a Map to retrieve generated token and conversation Id which is valid for that token.
public Map<String, Object> getDirectLineToken(String conversationId) {
Map<String, Object> responseMap = new LinkedHashMap();
StringBuilder url = new StringBuilder();
//Here we check conversation id
if(conversationId!=null && conversationId.length()!=0)
{
//If conversation id is already existing, then resume that conversation without generating new token for a new conversation
url.append("https://directline.botframework.com/v3/directline/conversations/").append(conversationId);
requestMethod = "GET";
}
else
{
//If there is no conversation id , then generate a direct line token and conversation id that can be used to initiate a new conversation by client application
url.append("https://directline.botframework.com/v3/directline/tokens/generate");
requestMethod = "POST";
}
URL urlObj = new URL(url.toString());
con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod(requestMethod);
//Here we are using generated secret to add authorization headers
con.setRequestProperty("Authorization","Bearer "+secret);
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Accept","application/x-www-form-urlencoded");
//if conversation id received as an input, is null, we need to generate new token and it is a POST request. Then you can set user id and name as the POST request payload. It will help direct line to perform additional security validations.
if(conversationId==null || conversationId.length()==0 )
{
JsonObject jsonObj = Json.createObjectBuilder()
.add("user", Json.createObjectBuilder()
.add("id",userId))
.build();
con.setDoOutput(true);
try (OutputStream os = con.getOutputStream()) {
os.write(jsonObj.toString().getBytes());
os.flush();
}
}
//sending request to direct line to generate new token
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
switch (responseCode) {
//if the request is successful, you will get a new token and conversation id. These information can be used by client application to initiate a new conversation with bot.
case HttpURLConnection.HTTP_OK:
//created
JsonObject jsonResponse = Json.createReader(con.getInputStream()).readObject();
String convId = jsonResponse.getString("conversationId");
String token = jsonResponse.getString("token");
responseMap.put("Conversation Id", convId );
responseMap.put("Token", token);
break;
case HttpURLConnection.HTTP_BAD_REQUEST:
case HttpURLConnection.HTTP_NOT_FOUND:
return getDirectLineToken(null);
//Above type of responses can be received when conversation id is expired. At that type of situations, you can call above same procedure with an input which is an empty conversation id
default:
System.out.println("POST request not worked");
break;
}
//if get OK response, response map will contain the conversation id and token valid for that conversation id.
return responseMap;
}
Difference between Start conversation and Generate conversation is
When you add your client application as a site to communicate with your bot framework through azure portal, bot framework will generate secret keys. Your client application can use these generated secret keys to authenticate direct line requests issued to your bot framework.
Let me explain how we can generate token to start a conversations between your own client and bot framework.
When we send a request to direct line for generating token, if the request is successful it will send the conversation id and token that is valid to that conversation id.
If client application already has a earlier used conversation Id, you can pass that id as an input to this method for generating token. If there is no conversation id, you can pass null value. Return type of this method is a Map to retrieve generated token and conversation Id which is valid for that token.
public Map<String, Object> getDirectLineToken(String conversationId) {
Map<String, Object> responseMap = new LinkedHashMap();
StringBuilder url = new StringBuilder();
//Here we check conversation id
if(conversationId!=null && conversationId.length()!=0)
{
//If conversation id is already existing, then resume that conversation without generating new token for a new conversation
url.append("https://directline.botframework.com/v3/directline/conversations/").append(conversationId);
requestMethod = "GET";
}
else
{
//If there is no conversation id , then generate a direct line token and conversation id that can be used to initiate a new conversation by client application
url.append("https://directline.botframework.com/v3/directline/tokens/generate");
requestMethod = "POST";
}
URL urlObj = new URL(url.toString());
con = (HttpURLConnection) urlObj.openConnection();
con.setRequestMethod(requestMethod);
//Here we are using generated secret to add authorization headers
con.setRequestProperty("Authorization","Bearer "+secret);
con.setRequestProperty("Content-Type", "application/json;odata=verbose");
con.setRequestProperty("Accept","application/x-www-form-urlencoded");
//if conversation id received as an input, is null, we need to generate new token and it is a POST request. Then you can set user id and name as the POST request payload. It will help direct line to perform additional security validations.
if(conversationId==null || conversationId.length()==0 )
{
JsonObject jsonObj = Json.createObjectBuilder()
.add("user", Json.createObjectBuilder()
.add("id",userId))
.build();
con.setDoOutput(true);
try (OutputStream os = con.getOutputStream()) {
os.write(jsonObj.toString().getBytes());
os.flush();
}
}
//sending request to direct line to generate new token
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
switch (responseCode) {
//if the request is successful, you will get a new token and conversation id. These information can be used by client application to initiate a new conversation with bot.
case HttpURLConnection.HTTP_OK:
//created
JsonObject jsonResponse = Json.createReader(con.getInputStream()).readObject();
String convId = jsonResponse.getString("conversationId");
String token = jsonResponse.getString("token");
responseMap.put("Conversation Id", convId );
responseMap.put("Token", token);
break;
case HttpURLConnection.HTTP_BAD_REQUEST:
case HttpURLConnection.HTTP_NOT_FOUND:
return getDirectLineToken(null);
//Above type of responses can be received when conversation id is expired. At that type of situations, you can call above same procedure with an input which is an empty conversation id
default:
System.out.println("POST request not worked");
break;
}
//if get OK response, response map will contain the conversation id and token valid for that conversation id.
return responseMap;
}
Difference between Start conversation and Generate conversation is
- Generate Conversation is just generating a direct line token and conversation id.Client application can use those information to initiate a new conversation with bot.
- Start Conversation will start a new conversation with bot
This was actually what i was looking for,and i am glad to came here you keep up the fantastic work!my weblog.. I like the trend that content is becoming more and more important.
ReplyDeleteChatbot Company in Dubai
Chatbot Companies in Dubai
Chatbot Development
Chatbot Companies
AI Chatbot Development
Chatbot Companies in UAE
Chatbot Company in Chennai
Chatbot Company in Mumbai
AI Chatbot Companies
Chatbot Development Companies