文档首页> 5G消息 Message over 5G> 开发指南> API代码样例> JAVA> 带建议回复消息的多卡片5G消息
更新时间:2024-04-28 GMT+08:00
分享

带建议回复消息的多卡片5G消息

代码样例

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
 
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
 
import com.fasterxml.jackson.databind.ObjectMapper;
 
import static java.nio.charset.StandardCharsets.UTF_8;
 
/**
 * 功能描述
 */
public class FivegMessageOutBoundMultiCardMessageWithResponse {
    // 带有值的返回成功状态码
    static final int SUCCESS_200_RES = 200;
 
    // 带有值的返回成功状态码
    static final int SUCCESS_201_RES = 201;
 
    // 不带值的返回成功状态码
    static final int SUCCESS_204_RES = 204;
 
    /**
     * 设置不验证主机
     */
 
    private static final HostnameVerifier DO_NOT_VERIFY = (hostname, session) -> true;
 
 
    private FivegMessageOutBoundMultiCardMessageWithResponse() {
    }
 
    /**
     * 多卡片发送消息
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
 
        Logger logger = Logger.getLogger(FivegMessageOutBoundMultiCardMessageWithResponse.class.getName());
        logger.setLevel(Level.WARNING);
 
        trustAllHttpsCertificates();
        URL realUrl = getUrl();
 
        HttpsURLConnection connection = (HttpsURLConnection) realUrl.openConnection();
 
        // 设置请求方式
        connection.setDoOutput(true);
        connection.setHostnameVerifier(DO_NOT_VERIFY);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Authorization", "Username=\"chatbottest12swt96\", Password=\"******\"");
        connection.setRequestProperty("Content-Type", "application/json");
        ObjectMapper objectMapper = new ObjectMapper();
        PrintWriter pw = new PrintWriter(new OutputStreamWriter(connection.getOutputStream(), UTF_8));
        pw.write(objectMapper.writeValueAsString(getMap()));
        pw.flush();
 
        connection.connect();
        int status = connection.getResponseCode();
        logger.warning("5GMessageResponse status: " + status);
        InputStream is;
        if (status != SUCCESS_200_RES) {
            if (status == SUCCESS_201_RES) {
                is = connection.getInputStream();
            } else if (status == SUCCESS_204_RES) {
                logger.warning("No Content Success");
                is = connection.getInputStream();
            } else { // error
                logger.warning("Error, DELETE status: " + status);
                is = connection.getErrorStream();
            }
        } else { // 200
            logger.warning("OK,DELETE Success, DELETE status: " + status);
            is = connection.getInputStream();
        }
 
        if (is != null) {
            BufferedReader br;
            br = new BufferedReader(new InputStreamReader(is, UTF_8));
            String line;
            StringBuilder result = new StringBuilder();
 
            // 读取数据
            while ((line = br.readLine()) != null) {
                result.append(line + System.lineSeparator().intern());
            }
            br.close();
            logger.warning("Content: " + result.toString());
 
            // 关流
            is.close();
        }
 
 
        // 关闭连接
        connection.disconnect();
    }
 
    /**
     * 获取URL
     *
     * @return url
     * @throws MalformedURLException
     */
    public static URL getUrl() throws MalformedURLException {
        URL realUrl;
 
        // CSP接口 不需要sag带tid字段
        String cspUrl = "https://10.120.207.128:18323/openchatbot/v2/"
                + "sip:888.chatbot@botplatform.rcs.chinamobile.com/outbound";
 
        return new URL(cspUrl);
    }
 
    /**
     * 返回Body体
     *
     * @return Body
     */
    public static Map<String, Object> getMap() {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> childMap = new HashMap<>();
        Map<String, Object> childNextMap = new HashMap<>();
 
        childNextMap.put("capabilityId", "Chatbot");
        childNextMap.put("version","*;+g.3gpp.iari-ref=\"urn%3Aurn-7%3A3gpp-application.ims.iari.rcs.chatbot.sa\"");
 
        childMap.put("senderAddress", "sip:471412.huawei@botplatform.rcs.chinamobile.com");
        childMap.put("address", "sip:+8613911111018@ims.mnc000.mcc460.3gppnetwork.org");
        childMap.put("destinationAddress", "sip:+8613911111018@ims.mnc000.mcc460.3gppnetwork.org");
        childMap.put("bodyText", "\n--next\nContent-Type: application/vnd.gsma.botmessage.v1.0+json\nContent-Disposition: inline; filename=\"Message\"\nContent-Length: [content length]\n\n{\n    \"message\": {\n        \"generalPurposeCardCarousel\": {\n            \"layout\": {\n                \"cardWidth\": \"MEDIUM_WIDTH\"\n            },\n            \"content\": [\n                {\n                    \"media\": {\n                        \"mediaUrl\": \"https://cdn.server/path/media.mp4\",\n                        \"mediaContentType\": \"video/mp4\",\n                        \"thumbnailUrl\": \"https://cdn.server/path/media.png\",\n                        \"thumbnailContentType\": \"image/png\",\n                        \"height\": \"SHORT_HEIGHT\"\n                    },\n                    \"title\": \"This is the first rich card in a carousel.\",\n                    \"description\": \"This is the description of the rich card. It's the first field that will be truncated if it exceeds the maximum width or height of a card.\",\n                    \"suggestions\": [\n                        {\n                            \"action\": {\n                                \"mapAction\": {\n                                    \"showLocation\": {\n                                        \"location\": {\n                                            \"latitude\": 37.4220041,\n                                            \"longitude\": -122.0862515,\n                                            \"label\": \"Googleplex\"\n                                        },\n                                        \"fallbackUrl\": \"https://www.google.com/maps/@37.4219162,-122.078063,15z\"\n                                    }\n                                },\n                                \"displayText\": \"Show location on a map\",\n                                \"postback\": {\n                                    \"data\": \"set_by_chatbot_open_map\"\n                                }\n                            }\n                        },\n                        {\n                            \"action\": {\n                                \"calendarAction\": {\n                                    \"createCalendarEvent\": {\n                                        \"startTime\": \"2017-03-14T00:00:00Z\",\n                                        \"endTime\": \"2017-03-14T23:59:59Z\",\n                                        \"title\": \"Meeting\",\n                                        \"description\": \"GSG review meeting\"\n                                    }\n                                },\n                                \"displayText\": \"Schedule Meeting\",\n                                \"postback\": {\n                                    \"data\": \"set_by_chatbot_create_calendar_event\"\n                                }\n                            }\n                        }\n                    ]\n                },\n                {\n                    \"title\": \"This is the second rich card in the carousel.\",\n                    \"description\": \"Carousel cards need to specify a card width in the 'layout' section. For small width cards, only short and medium height media are supported.\",\n                    \"[...]\": \"[...]\"\n                }\n            ]\n        }\n    }\n}\n\n--next\nContent-Type: application/vnd.gsma.botsuggestion.v1.0+json\nContent-Disposition: inline; filename=\"Chiplist.lst\"\nContent-Length: [content length]\n\n{\n\"suggestions\": [\n{\n\"reply\": {\n\"displayText\": \"Yes\",\n\"postback\": {\n\"data\": \"set_by_chatbot_reply_yes\"\n}}},\n{\n\"reply\": {\n\"displayText\": \"No\",\n\"postback\": {\n\"data\": \"set_by_chatbot_reply_no\"\n}}},\n{\n\"action\": {\n\"urlAction\": {\n\"openUrl\": {\n\"url\": \"https://www.google.com\"\n}},\n\"displayText\": \"Open website or deep link\",\n\"postback\": {\n\"data\": \"set_by_chatbot_open_url\"\n}}},\n{\n\"action\": {\n\"dialerAction\": {\n\"dialPhoneNumber\": {\n\"phoneNumber\": \"+1650253000\"\n}},\n\"displayText\": \"Call a phone number\",\n\"postback\": {\n\"data\": \"set_by_chatbot_open_dialer\"\n}}}]}\n--next--\n");
        childMap.put("destinationTerminal", "Native");
        childMap.put("imFormat", "IM");
        childMap.put("contentType", "multipart/mixed; boundary=\"next\"");
        childMap.put("serviceCapability", childNextMap);
 
        map.put("destinationAddress", "tel:+8613911111030");
        map.put("clientCorrelator", "567895");
        map.put("outboundIMMessage", childMap);
 
        return map;
    }
 
    static void trustAllHttpsCertificates() throws Exception {
        TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
                return;
            }
 
            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
                return;
            }
 
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }
        };
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }
 
}
表1 代码样例中可变参数说明

参数名称

参数说明

url

请求地址

Map

封装请求发送的信息、参数

Connection

封装建立连接的认证信息、请求方式等

消息样例

resultMsg.toString(){"senderAddress":"******","senderName":"Default Name","address":"******","destinationAddress":"******","clientCorrelator":"567895","outboundIMMessage":{"contributionID":"c67771cf-bd31-483e-8f8a-479df74db92e","storeSupported":"true","bodyText":"******","reportRequest":["Delivered","Displayed","Failed"],"conversationID":"fSFDSFDR$%#$%$%$%","subject":"Default Subject","shortMessageSupported":"false","contentEncoding":"utf8","contentType":"multipart/mixed; boundary=\"next\"","serviceCapability":[{"capabilityId":"ChatbotSA","version":"+g.gsma.rcs.botversion=\"#=1\""},{"capabilityId":"ChatbotSA222","version":"+g.gsma.rcs.botversion=\"#=1\""}]}}
分享:

    相关文档

    相关产品