首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

Urban Airship Server API - Java客户端范例

2012-11-23 
Urban Airship Server API - Java客户端实例本文链接:http://blog.csdn.net/kongxx/article/details/81604

Urban Airship Server API - Java客户端实例

本文链接:http://blog.csdn.net/kongxx/article/details/8160493

今天在看Urban Airship的server端的API,Urban Airship官方网站上推荐了一个第三方的开源库http://bitbucket.org/sullis/urbanairship-java/,但是在经过简单测试后还是发现了一些问题,并且这个库好像也不是很活跃。为了看看Urban Airship的server端API怎么用,自己还是决定自己写个小程序试试看。

今天的测试由于涉及从Urban Airship向Android设备发送消息,所以这里假定已经有Android设备或者模拟器安装了可以接收消息的native app,具体步骤可以参考我的前一篇博客(http://blog.csdn.net/kongxx/article/details/8155916)。

下面开始今天的测试

1. 首先创建一个工程,这里还是使用maven来创建工程

package urbanairship.server;import java.io.UnsupportedEncodingException;import java.util.logging.Level;import java.util.logging.Logger;import org.apache.http.Header;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.StatusLine;import org.apache.http.auth.AuthScope;import org.apache.http.auth.UsernamePasswordCredentials;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicHeader;import org.apache.http.util.EntityUtils;public class Test {private static Logger logger = Logger.getLogger(Test.class.getName());private static final String username = "This should be Application Key";private static final String password = "This should be Application Master Secret";private static final String apid = "This should be your APID of your android device";public static void main(String[] args) throws Exception {StringBuffer sb = new StringBuffer();sb.append("{\"android\": {\"alert\": \"hello world\"}, \"apids\": [\""+apid+"\"]}");String path = "https://go.urbanairship.com/api/push/";DefaultHttpClient httpClient = new DefaultHttpClient();httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));HttpPost httpPost = new HttpPost(path);httpPost.setHeader("Accept", "application/json");httpPost.setEntity(new JsonEntity(sb.toString()));logger.log(Level.INFO, "executing request: " + httpPost.getRequestLine());HttpResponse response = httpClient.execute(httpPost);StatusLine status = response.getStatusLine();int statusCode = status.getStatusCode();logger.log(Level.INFO, ""+statusCode);HttpEntity responseEntity = response.getEntity();logger.log(Level.INFO,  EntityUtils.toString(responseEntity));}static private class JsonEntity extends StringEntity {public JsonEntity(String jsonString) throws UnsupportedEncodingException {super(jsonString, "UTF-8");}@Overridepublic Header getContentType() {Header h = new BasicHeader("Content-Type", "application/json");return h;}}}
4. 测试,首先运行模拟器,然后运行可以接收message的android native app,最后运行上面的测试类,稍等片刻就会在设备或者模拟器上看到消息了。







热点排行