Java calls third-party interface-Post method

This article is an application of WeChat customer service in Enterprise WeChat. The entire logic is: WeChat users send requests, and Enterprise WeChat customer service responds by judging whether the time of receiving the message is on a working day.

Difficulty 1: Calling the interface

Read interface call:

Step 1: Get the link to the interface

 String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/kf/sync_msg?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN",sToken.getToken());

Step 2: Check whether the interface needs to add input parameters

Because the Post method needs to splice JSON type data, it requires JSONObject.

JSONObject jo = new JSONObject();
jo.put("cursor",""); //上一次调用时返回的next_cursor,第一次拉取可以不填
jo.put("limit",String.valueOf(1000));//期望请求的数据量
jo.put("voice_format",String.valueOf(0));//语音消息类型
String openKfid = "wkKqpJCAAAVfANm88k_s1HfnYYFFfgLw";
jo.put("open_kfid",openKfid);//指定拉取李西客服帐号的消息
// 读取消息接口 的调用
JSONObject jsonObject = WeixinUtil.HttpRequest(requestUrl,"POST", JSON.toJSONString(jo));

Difficulty 2: Operation of the return result of the interface

Send interface call

Step 1: Get the link to the interface

String requestUrl2 = "https://qyapi.weixin.qq.com/cgi-bin/kf/send_msg?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN",sToken.getToken());

Step 2: Operate the return results of the reading interface

The following figure shows the return result of the reading interface. Because it is of {} type, the return result is of JSONObject type.

The parameters used are:

open_kfid represents the customer service account;

external_userid represents the WeChat user’s account;

send_time means that the WeChat user sends the message, which is the time when the enterprise WeChat customer service receives the message.

So msg_list in jsonObject is used

 JSONArray msgList =(JSONArray)jsonObject.get("msg_list");//消息列表
 String s = JSONObject.toJSONString(msgList);
 List<HashMap<String,Object>> msgList1 =  (List<HashMap<String,Object>>)msgList.parse(s);
 Map<String,Object> map = msgList1.get(msgList1.size() - 1);

 logger.error("msgList1.get(msgList1.size() - 1)---------"+map);

It means that the desired msg_list has been obtained.

It is written in the API that origin == 3 means that the message is sent by a WeChat user, so it needs to be judged in advance.

String toUser = "";
Long timeRequest = null;
if(Integer.valueOf((Integer) map.get("origin")) == 3){
        //读取消息传过来的微信用户id
          toUser = (String) map.get("external_userid");  
          logger.error("toUser-------"+toUser);
        //读取消息传过来的发送消息的时间戳
          Integer i =(Integer) map.get("send_time");  //将Integer 转 Long
          long l = i;
          timeRequest = l;  
          logger.error("send_time-------"+timeRequest);
}

Step 3: Use the return result of the reading interface as the parameter of the sending interface

Process the send_time obtained in the second step to determine whether the message is sent by a robot or transferred to human customer service

       /**
        * 判断是否是周末
        * @param date
         * @return
        */
        public static boolean isWeekend(Date date){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
            return dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY;
        }

        /**
        * 判断是否是工作时间
        * @param sendTime    传进来的时间戳
        * @param startWork   开始工作的时间
        * @param endWork     结束工作的时间
        * @return
        */
        public static boolean isWorkTime(Long sendTime,String startWork,String endWork) throws ParseException {
            Long sendTime1 = sendTime*1000;
            Date send = new Date(sendTime1);
            if (!isWeekend(send)){
                LocalDateTime localDateTime = send.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
                LocalTime send1 = localDateTime.toLocalTime();
                LocalTime start = LocalTime.parse(startWork, DateTimeFormatter.ofPattern("HH:mm:ss"));
                LocalTime end = LocalTime.parse(endWork, DateTimeFormatter.ofPattern("HH:mm:ss"));
                int sendStart = send1.compareTo(start);
                int sendEnd = send1.compareTo(end);
                if (sendStart >= 0 && sendEnd <= 0){
                    return true;
                }
                return false;
            }
            return false;
        }

When using the sending interface, you need to pass parameters. The example is as follows:

So operate on the return results of the methods that read the interface:

boolean isWorkTime = DateFormatUtil.isWorkTime(timeRequest, "09:00:00", "18:00:00");
//判断是否是工作时间
if(isWorkTime){
      JSONObject joSend = new JSONObject();
      joSend.put("touser",toUser);
      joSend.put("open_kfid",openKfid);
      joSend.put("msgtype","text");
    //输出内容 或者是 自动回复的内容
      Map mapText = new HashMap();
      mapText.put("content","工作时间,会话消息测试---------------");
      joSend.put("text",mapText);
}

Call interface:

JSONObject jsonObject1 = WeixinUtil.HttpRequest(requestUrl2,"POST",JSON.toJSONString(joSend));

final output result

Guess you like

Origin blog.csdn.net/xy58451921/article/details/129794720