微信公众号开发_调用新闻查询接口_回复图文消息


发送效果:
在这里插入图片描述

一、新闻API接口

使用的是阿里云市场的服务

在这里插入图片描述

全国热门带正文新闻查询API接口
使用方式很简单:
我已经写好的代码:
实体类:
用来接收返回的json数据

返回的Json示例

{
	"showapi_res_code": 0,
	"showapi_res_error": "",
	"showapi_res_body": {
		"ret_code": 0,
		"pagebean": {
			"allPages": 5,   //所有页数
			"contentlist": [  //数据条目列表
				{
					"allList": [   //数据条目列表
						{
							"height": 433,   //图片高
							"width": 650,    //宽
							"url": "http://p3.ifengimg.com/cmpp/2016/07/11/10/07fd6e97-684f-4c1d-858c-900acb1fc7d3_size87_w650_h433.jpg"   //图片地址
						},
						"凤凰娱乐讯 《挑战者联盟》第二季自播出以来,热议不断。在上周六晚20:30播出的功夫主题节目中,“功夫潮男”向佐大展身手,与挑战者联盟成员一起,为观众奉献了一场精彩绝伦的综艺热血秀。",
						{
							"height": 856,
							"width": 600,
							"url": "http://p2.ifengimg.com/cmpp/2016/07/11/10/51a88903-475f-49f9-9ffa-47910209e309_size86_w600_h856.jpg"
						},
						"本期《挑战者联盟》嘉宾们上演“全武行”,还原经典电影武打场面!在《少林足球》经典场景中,向佐带领的“梅门”与挑战者们将一决高下!挑盟成员使出浑身解数,场上局势陷入胶着。陈学冬、薛之谦拼命想要阻拦向佐,却被肌肉贲张的向佐一把扛在肩上,轻松带走!薛之谦只好耍赖胡搅蛮缠,和向佐变成“大鹰捉小鸡”,紧抓向佐衣服不放,躺地被拖数米,不想向佐直接“爆衣”,一秒挣开薛之谦的控制,令薛之谦瞬间傻眼呆立场上!众人在球门前扭成一团,战况激烈得连球门都掀起,令人啼笑皆非热闹非凡。",
						"节目中,向佐的精彩表现,更被网友赞为:新一代“综艺小魔王”"
					],
					"pubDate": "2016-07-11 12:05:29",
					"title": "《挑战者联盟》还原少林足球 薛之谦耍赖被”爆衣“",
					"channelName": "娱乐最新",
					"imageurls": [
						{
							"height": 433,
							"width": 650,
							"url": "http://p3.ifengimg.com/cmpp/2016/07/11/10/07fd6e97-684f-4c1d-858c-900acb1fc7d3_size87_w650_h433.jpg"
						},
						{
							"height": 856,
							"width": 600,
							"url": "http://p2.ifengimg.com/cmpp/2016/07/11/10/51a88903-475f-49f9-9ffa-47910209e309_size86_w600_h856.jpg"
						}
					],
					"desc": "《挑战者联盟》第二季自播出以来,热议不断。在上周六晚20:30播出的功夫主题节目中,“功夫潮男”向佐大展身手,与挑战者联盟成员一起,为观众奉献了一场精彩绝伦的综艺热。薛之谦只好耍赖胡搅蛮缠,和向佐变成“大鹰捉小鸡”,紧抓向佐衣服不放,躺地被拖数米,不想向佐直接“爆衣”,一秒挣开薛之谦的控制,令薛之谦瞬间傻眼呆立场上!",
					"source": "凤凰娱乐",
					"channelId": "5572a10ab3cdc86cf39001eb",
					"nid": "14300662248981139731",
					"link": "http://ent.ifeng.com/a/20160711/42649589_0.shtml"  //新闻详情链接
				} 
			],
			"currentPage": 1,
			"allNum": 96,
			"maxResult": 20
		}
	}
}

实体类

@Data
public class ContentList {
    /**
     * 日期
     */
    private  String pubDate;
    /**
     * 新闻频道   国内焦点
     */
    private  String channelName;
    private  String channelId;
    /**
     * 新闻链接
     */
    private  String link;
    private  String img;
    private  String allList;
    /**
     * 新闻标题
     */
    private  String title;
    /**
     * 网易新闻
     */
    private  String source;

}
@Data
public class News {
    private String showapi_res_error;
    private String showapi_res_id;
    private String showapi_res_code;
    private String showapi_res_body;
}

@Data
public class PageBean {
    private String allPages;
    /**
     * 数组
     */
    private String contentlist;
    private String currentPage;
    private String allNum;
    private String maxResult;
}

@Data
public class ShowapiResBody {
    private String ret_code;
    private String pagebean;
}

测试类测试

@SpringBootTest
public class NewsTest {
    @Test
    public void test(){
            String host = "http://ali-news.showapi.com";
            String path = "/newsList";
            String method = "GET";
            String appcode = "3b659fb1d3a0478d9e55621e6f87632b";
            Map<String, String> headers = new HashMap<String, String>();
            //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
            headers.put("Authorization", "APPCODE " + appcode);
            Map<String, String> querys = new HashMap<String, String>();
            //新闻频道id,必须精确匹配  国内焦点
            // querys.put("channelId", "5572a108b3cdc86cf39001cd");
            //娱乐最新
            querys.put("channelId", "5572a10ab3cdc86cf39001eb");
            //新闻频道名称,可模糊匹配
            querys.put("channelName", "");
            //新闻id,可用此信息取得一条新闻记录
            querys.put("id", "");
            //每页最大请求数,默认是20
            querys.put("maxResult", "10");
            //是否需要返回所有的图片及段落属行allList。
            querys.put("needAllList", "0");
            //是否需要返回正文,1为需要,其他为不需要
            querys.put("needContent", "0");
            //是否需要返回正文的html格式,1为需要,其他为不需要
            querys.put("needHtml", "0");
            //页数,默认1。每页最多20条记录。
            querys.put("page", "1");
            //标题名称,可模糊匹配
            querys.put("title", "");
            try {
                /**
                 * 重要提示如下:
                 * HttpUtils请从
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
                 * 下载
                 *
                 * 相应的依赖请参照
                 * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
                 */
                HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
                System.out.println(response.toString());
                //获取response的body
                HttpEntity entity = response.getEntity();
                String respJsonStr = EntityUtils.toString(response.getEntity());
                System.out.println(respJsonStr);
                //将josn字符串解析成JSONObject
                JSONObject jsonObject = JSONObject.parseObject(respJsonStr);
                System.out.println("jsonObject:"+jsonObject);
                //从JSONObject中提取contentlist
                JSONObject body = (JSONObject) jsonObject.get("showapi_res_body");
                JSONObject pagebean = (JSONObject) body.get("pagebean");
                String contentlist = pagebean.get("contentlist").toString();
                System.out.println(pagebean.get("contentlist").toString());
                //解析contentlist为ContentList集合
                List<ContentList> contentLists = JSONObject.parseArray(contentlist, ContentList.class);
                System.out.println("ContentList集合:"+contentLists.size());
                for (ContentList contentList : contentLists) {
                    System.out.println("日期"+contentList.getPubDate());
                    System.out.println("新闻频道"+contentList.getChannelName());
                    System.out.println("图片地址"+contentList.getImg());
                    System.out.println("新闻链接"+contentList.getLink());
                    System.out.println("新闻标题"+contentList.getTitle());
                    System.out.println("新闻媒体"+contentList.getSource());
                    System.out.println("-------------------------------------");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
}

二、发送图文消息

xml数据格式

<xml>
  <ToUserName><![CDATA[toUser]]></ToUserName>
  <FromUserName><![CDATA[fromUser]]></FromUserName>
  <CreateTime>12345678</CreateTime>
  <MsgType><![CDATA[news]]></MsgType>
  <ArticleCount>1</ArticleCount>
  <Articles>
    <item>
      <Title><![CDATA[title1]]></Title>
      <Description><![CDATA[description1]]></Description>
      <PicUrl><![CDATA[picurl]]></PicUrl>
      <Url><![CDATA[url]]></Url>
    </item>
  </Articles>
</xml>

实体类

@Data
@XStreamAlias("xml")
public class BaseMessage {
    @XStreamAlias("ToUserName")
    private String toUserName;
    @XStreamAlias("FromUserName")
    private String fromUserName;
    @XStreamAlias("CreateTime")
    private String createTime;
    @XStreamAlias("MsgType")
    private String msgType;
    @XStreamAlias("MsgId")
    private String msgId;


    public BaseMessage(Map<String ,String> map){
        this.fromUserName=map.get("ToUserName");
        this.toUserName=map.get("FromUserName");
        this.createTime = System.currentTimeMillis()/1000+"";
    }
    public BaseMessage(){

    }
}

@Data
@XStreamAlias("xml")
public class NewsMessage extends BaseMessage {
    /**
     * 图文消息信息,注意,如果图文数超过限制,则将只发限制内的条数
     */
    @XStreamAlias("Articles")
    private Item[] articles;
    /**
     * 图文消息个数;
     * 当用户发送文本、图片、语音、视频、图文、地理位置这六种消息时,开发者只能回复1条图文消息;
     * 其余场景最多可回复8条图文消息
     */
    @XStreamAlias("ArticleCount")
    private int ArticleCount;
    public NewsMessage(Map<String ,String> map, Item[] item){
        super(map);
        this.setMsgType("news");
        this.articles = item;
    }

    public NewsMessage(){

    }
}

@Data
@XStreamAlias("item")
public class Item {
    private String Title;
    private String Description;
    private String PicUrl;
    private String Url;
}

创建自定义菜单

创建自定义菜单的方法就不多解释:

        SubButton subButton = new SubButton("新闻资讯");
//        subButton.getSub_button().add(new PhotoAlbumButton("拍照或相册发图","pic_photo_or_album","rselfmenu_1_0"));
        subButton.getSub_button().add(new ClickButten("国内焦点","V1003_TODAY_NEWS"));
        subButton.getSub_button().add(new ClickButten("国际焦点","V1004_TODAY_NEWS"));
        subButton.getSub_button().add(new ClickButten("财经焦点","V1005_TODAY_NEWS"));
        subButton.getSub_button().add(new ClickButten("娱乐焦点","V1006_TODAY_NEWS"));

处理点击事件

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

查询新闻工具类

@Component
public class NewUtil {
    private static final String host = "http://ali-news.showapi.com";
    private static final String path = "/newsList";
    private static final String method = "GET";
    private static final String appcode = "3b659fb1d3a0478d9e55621e6f87632b";
    //娱乐焦点
    private static final String ylchannelId = "5572a10ab3cdc86cf39001eb";
    //国内焦点
    private static final String gnchannelId = "5572a108b3cdc86cf39001cd";
//    private static final String method = "GET";
    public Item[] getNews(String channelId){
        Item[] items = new Item[8];
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);
        Map<String, String> querys = new HashMap<String, String>();
        //新闻频道id,必须精确匹配
        querys.put("channelId", channelId);
        //新闻频道名称,可模糊匹配
        querys.put("channelName", "");
        //新闻id,可用此信息取得一条新闻记录
        querys.put("id", "");
        //每页最大请求数,默认是20
        querys.put("maxResult", "8");
        //是否需要返回所有的图片及段落属行allList。
        querys.put("needAllList", "0");
        //是否需要返回正文,1为需要,其他为不需要
        querys.put("needContent", "0");
        //是否需要返回正文的html格式,1为需要,其他为不需要
        querys.put("needHtml", "0");
        //页数,默认1。每页最多20条记录。
        querys.put("page", "1");
        //标题名称,可模糊匹配
        querys.put("title", "");
        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
            System.out.println(response.toString());
            //获取response的body
            HttpEntity entity = response.getEntity();
            String respJsonStr = EntityUtils.toString(response.getEntity());
            System.out.println(respJsonStr);
            //将josn字符串解析成JSONObject
            JSONObject jsonObject = JSONObject.parseObject(respJsonStr);
            System.out.println("jsonObject:"+jsonObject);
            //从JSONObject中提取contentlist
            JSONObject body = (JSONObject) jsonObject.get("showapi_res_body");
            JSONObject pagebean = (JSONObject) body.get("pagebean");
            String contentlist = pagebean.get("contentlist").toString();
            System.out.println(pagebean.get("contentlist").toString());
            //解析contentlist为ContentList集合
            List<ContentList> contentLists = JSONObject.parseArray(contentlist, ContentList.class);
            System.out.println("ContentList集合:"+contentLists.size());
            for (int i = 0; i < contentLists.size() ; i++) {
                ContentList contentList = contentLists.get(i);
                Item item = new Item();
                item.setUrl(contentList.getLink());
                String defaultImgUrl = "";
                defaultImgUrl = contentList.getImg();
                if ("null".equals(defaultImgUrl)||null == defaultImgUrl){
                     defaultImgUrl = "http://mmbiz.qpic.cn/mmbiz_jpg/G6FDfpc5D6nMJnbfic9pTng5kVeKRkQBVfMCbcKcYB6xsfMSekD4EoR2o7gW7nVkCpLhicCGFCu3icG4DDmr2KDGg/0";
                }
                item.setPicUrl(defaultImgUrl);
                item.setTitle(contentList.getTitle());
                item.setDescription(contentList.getTitle());
                items[i] = item;
                System.out.println("日期"+contentList.getPubDate());
                System.out.println("新闻频道"+contentList.getChannelName());
                System.out.println("图片地址"+defaultImgUrl);
                System.out.println("新闻链接"+contentList.getLink());
                System.out.println("新闻标题"+contentList.getTitle());
                System.out.println("新闻媒体"+contentList.getSource());
                System.out.println("-------------------------------------"); 
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return items;
    }
}

仓库代码地址

代码已上传Gitee仓库:仓库代码地址

关注微信公众号

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liu_Shihao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值