メッセージ内のテキストをタップしてポストバックを実行する方法は、LINEの「テキストリンクアクション」を使用する
LINE Messaging API SDKを使用せずに、JavaでHTTP通信を直接行ってテキストリンクアクションを含むFlex Messageを送信する方法を説明します。この例では、Java標準のHTTPクライアントとJSONライブラリ(org.json)を使用します。
まず、必要なライブラリをプロジェクトに追加してください:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20210307</version>
</dependency>
以下は、テキストリンクアクションを含むFlex Messageを作成し、LINEのAPIエンドポイントに送信するJavaコードです:
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import org.json.JSONObject;
import org.json.JSONArray;
public class LineMessageSender {
private static final String LINE_MESSAGING_API = "https://api.line.me/v2/bot/message/push";
private static final String CHANNEL_ACCESS_TOKEN = "YOUR_CHANNEL_ACCESS_TOKEN";
public static void sendTextLinkMessage(String userId) throws Exception {
URL url = new URL(LINE_MESSAGING_API);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Authorization", "Bearer " + CHANNEL_ACCESS_TOKEN);
con.setDoOutput(true);
JSONObject flexMessage = createFlexMessage();
JSONObject body = new JSONObject();
body.put("to", userId);
body.put("messages", new JSONArray().put(flexMessage));
try(OutputStream os = con.getOutputStream()) {
byte[] input = body.toString().getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
con.disconnect();
}
private static JSONObject createFlexMessage() {
JSONObject flexMessage = new JSONObject();
flexMessage.put("type", "flex");
flexMessage.put("altText", "テキストリンクの例");
JSONObject contents = new JSONObject();
contents.put("type", "bubble");
JSONObject body = new JSONObject();
body.put("type", "box");
body.put("layout", "vertical");
JSONObject text = new JSONObject();
text.put("type", "text");
text.put("text", "ここをタップしてください");
JSONObject action = new JSONObject();
action.put("type", "postback");
action.put("label", "ポストバック");
action.put("data", "action=tapped");
action.put("displayText", "テキストがタップされました");
text.put("action", action);
body.put("contents", new JSONArray().put(text));
contents.put("body", body);
flexMessage.put("contents", contents);
return flexMessage;
}
public static void main(String[] args) {
try {
sendTextLinkMessage("USER_ID");
} catch (Exception e) {
e.printStackTrace();
}
}
}
このコードでは以下の主要な部分があります:
-
createFlexMessage()
メソッドで、テキストリンクアクションを含むFlex Messageを作成します。 -
sendTextLinkMessage()
メソッドで、作成したメッセージをLINE Messaging APIに送信します。 - HTTPリクエストのヘッダーに
Authorization
を設定し、Channel Access Tokenを指定します。 - リクエストボディにJSON形式でメッセージデータを設定します。
使用する際は、CHANNEL_ACCESS_TOKEN
を自分のチャンネルのアクセストークンに、USER_ID
を送信先のユーザーIDに置き換えてください。
このコードを実行すると、指定したユーザーに対してテキストリンクを含むFlex Messageが送信されます。ユーザーがテキストをタップすると、"テキストがタップされました"というメッセージが表示され、同時に"action=tapped"というデータがサーバーに送信されます。
Perplexity の Eliot より: pplx.ai/share