更新时间:2024-11-21 GMT+08:00
分享

单卡片5G消息发送

代码样例

package Demo;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
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.SSLSession;
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 SingleCardMs2 {

     static final int SUCCESS = 200;
     static final int ERR = 204;

 
private static final HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {

         @Override
         public boolean verify(String hostname, SSLSession session) {

             return true;

         }

     };




     /**
      * 单卡片消息请求
      */
     public static void main(String[] args) throws Exception {


         Map<String, Object> map1 = new HashMap<>();
         map1.put("contributionID","contributionID");
         map1.put("senderAddress","sip:471400.huawei@botplatform.rcs.chinamobile.com");
         map1.put("address","sip:+8613911111018@ims.mnc000.mcc460.3gppnetwork.org");
         map1.put("destinationAddress","sip:+8613911111018@ims.mnc000.mcc460.3gppnetwork.org");
         map1.put("bodyText","\\n{\\n    \\\"message\\\": {\\n        \\\"generalPurposeCardCarousel\\\": {\\n            \\\"layout\\\": {\\n                \\\"cardWidth\\\": \\\"MEDIUM_WIDTH\\\"\\n            },\\n            \\\"content\\\": [\\n                {\\n                    \\\"media\\\": {\\n                        \\\"mediaUrl\\\": \\\"http://10.243.50.178:9090/Access/PF?ID=Q0Q5QjAxRUU1NDBFRDUxQUQ5RkFFOTY0RjQ3MjM4NjBGQkM2NDFDNzQ2OTBCMENBOUJDRjlBRUE3Q0U0NDA5NTA3QkQ4M0UxNzM4NzlERTJCQzMxNEM5QUFDRDg2Nzg1\\\",\\n                        \\\"mediaContentType\\\": \\\"image/png\\\",\\n                        \\\"thumbnailUrl\\\": \\\"http://10.243.50.178:9090/Access/PF?ID=MkE2REU4QTQ2RjU4OEJBQjNBNDg3Q0ZCRUI0NUVBQzUxQUU1MkE5QjY0MDFCN0U5NkYwMzNFQjc5MjJGRDlGOEYxOTUwQjc5QUREQUFCRkY5ODBERUQ2ODMwNjEwOTY1\\\",\\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                \\t\\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");

 
         map1.put("conversationID","conversationID");
         map1.put("contentType","application/vnd.gsma.botmessage.v1.0+json");

         Map<String, Object> map = new HashMap<>();
         map.put("destinationAddress","tel:+8613911111030");
         map.put("clientCorrelator","567895");
         map.put("outboundIMMessage",map1);

         post("https://10.120.207.128:18323/openchatbot/v2/sip:888.chatbot@botplatform.rcs.chinamobile.com/outbound",map);
     }
     /**
      * 定义post方法
      */

     public static String post(String url, Map<String, Object> params) throws Exception {
         trustAllHttpsCertificates();
         Logger logger = Logger.getLogger(SingleCardMs2.class.getName());
         logger.setLevel(Level.WARNING);
         logger.warning("url" + url);

         URL url1 = new URL(url);
         InputStream is;

         // 将url以open方法返回的urlConnection连接强转为HttpURLConnection连接(标识一个url所引用的远程对象连接),此时cnnection只是为一个连接对象,待连接中
         HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();

         conn.setHostnameVerifier(DO_NOT_VERIFY);

         // 设置连接输出流为true,默认false (post请求是以流的方式隐式的传递参数)
         conn.setDoOutput(true);

         // 设置连接输入流为true
         conn.setDoInput(true);

         // 设置请求方式为post
         conn.setRequestMethod("POST");

         // post请求缓存设为false
         conn.setUseCaches(false);

         // 设置该HttpURLConnection实例是否自动执行重定向
         conn.setInstanceFollowRedirects(true);

         // 设置内容的类型,设置为经过urlEncoded编码过的from参数
         conn.setRequestProperty("Content-Type", "application/json");
         conn.setRequestProperty("Authorization", 
"Username=\"chatbottest12swt96\",Password=\"******\"");



         ObjectMapper objectMapper = new ObjectMapper();
         PrintWriter pw = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), UTF_8));
         pw.write(objectMapper.writeValueAsString(params));

         // 查看传参信息
         logger.warning(objectMapper.writeValueAsString(params));
         pw.flush();
         pw.close();

         // 建立连接(请求未开始,直到connection.getInputStream()方法调用时才发起,以上各个参数设置需在此方法之前进行)
         conn.connect();


         // 连接发起请求,处理服务器响应 (从连接获取到输入流并包装为bufferedReader)
         int status = conn.getResponseCode();
         logger.warning("status:" + status);
         if (status != 200) {
             logger.warning("OK,SUCESSNo Content");
             if (status == 201) {
                 logger.warning("SUCESS BUT No Content");
                 is = conn.getInputStream();
             } else if (status == 204) {
                 logger.warning("err");
                 is = conn.getInputStream();
             } else { // 400/401
                 is = conn.getErrorStream();
             }
         } else { // 200
             logger.warning("OK,SUCESS");
             is = conn.getInputStream();
         }
BufferedReader br = new BufferedReader(new InputStreamReader(is, UTF_8));
         String line;
         StringBuilder resultMsg = new StringBuilder();
         while ((line = br.readLine()) != null) { // 读取数据
             resultMsg.append(line);
         }

         // 关流,这个很重要
         is.close();
         br.close();

         // 关闭连接
         conn.disconnect();
         logger.warning("resultMsg.toString()" + resultMsg.toString());
         return null;
     }

     static void trustAllHttpsCertificates() throws Exception {
         TrustManager[] trustAllCerts = new TrustManager[] {
                 new X509TrustManager() {
                     @Override
                     public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                         return;
                     }

                     @Override
                     public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                         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\""}]}}

相关文档