JAVA调用易信接口向指定好友推送消息(二)POST测试

易信的API接口做的还算简单

http://open.yixin.im/document/oauth/api

根据指南上的步骤,利用易信提供的测试ID

AppID(client_id): yxbbd0e8b3dce64e02bab42437becc4384       AppSecret:5a1db5830047b4a

可以很容易获得access_token,以及指定联系人的toAccountId

下面,利用前几篇博文提到的apache http组件,向易信的web service提交测试请求

package com.newflypig.demo;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

/**
 * 向易信服务器发送POST请求示例
 * @author newflydd
 * 易信授权的相关数据如下:
 * url:https://open.yixin.im/api/sendp2pmsg
 * access_token:b2421624-db5c-44d1-93f0-1e71f9cXXXXX
 * toAccountId:6c0f7514f4bdXXXX(唐蔚);fd60e46db0dc119cfea740c3375XXXXX(王群)
 * content:需要推送的数据
 * {"text_content": "这段文字发送自易信SDK示例程序,并且由服务器自动调用发送","desc": "不需要描述","type":"text"}
 * {
    "image": "http://img.hoop8.com/attachments/1510/911826782594.jpg",
    "title": "新增发展积分",
    "url": "http://img.hoop8.com/attachments/1510/911826782594.jpg",
    "type":"image"
    }
 *
 */

public class SendPostToYixin {

    public static void main(String[] args) throws Exception{
        HttpClient client=HttpClients.createDefault();
        HttpPost post=new HttpPost("https://open.yixin.im/api/sendp2pmsg");
        
        List<NameValuePair> parameters=new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("access_token", "b2421624-db5c-44d1-93f0-1e71f9cXXXXX"));
        parameters.add(new BasicNameValuePair("toAccountId", "fd60e46db0dc119cfea740c337XXXXX"));
        parameters.add(new BasicNameValuePair("content", "{\"text_content\":\"这段文字发送自易信SDK示例程序,并且由服务器自动调用发送\",\"desc\":\"不需要描述\",\"type\":\"text\"}"));
        
        post.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));
        
        HttpResponse response=client.execute(post);
        System.out.println(EntityUtils.toString(response.getEntity()));
    }
}

很简单,简单得我都不愿意多解释

对了,博主的access_token和toAccountId最后三个字母做了修改,否则的话大家都可以利用这两个参数以我的名义向好友发送消息了。

最后成功了以后,在易信客户端可以看到如下的效果:

posted on 2015-10-19 14:45  丁丁·全栈工程师  阅读(1236)  评论(1编辑  收藏  举报

导航