转:http://blog.csdn.net/heynine/article/details/8140000
调用JPush推送的api,官网上已经有很详细的说明了。这里主要描述一下我在调用过程中遇到的问题,
比如
我的HttpClient不支持https的请求、
参数配置错误 和 验证错误 等等。
开发的时候需要引用appache的包commons-httpclient.jar 、commons-codec.jar、commons-logging.jar这些包可以到官网上下载,如果有需要的话也我也可以发给你。
引入上述这些包之后,就可以进行开发了。
这里需要特别说明的两点是:
1、通过 HttpClient client = new DefaultHttpClient(); 获得HttpClient对象不支持https,需要自己重写。
2、我们的MD5编码要和服务器那边的一样。(我用我自己写的MD5编码验证的时候,总是验证失败,后来跟他们的技术人员要了他们的md5的实现方式就通过验证了)
好了,废话不多说了,接下来是贴代码的时候了:
类MySSLSocketFactory用来实现对https的支持
[java]
view plain
copy
- import java.io.IOException;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import java.security.KeyManagementException;
- import java.security.KeyStore;
- import java.security.KeyStoreException;
- import java.security.NoSuchAlgorithmException;
- import java.security.UnrecoverableKeyException;
- import java.security.cert.CertificateException;
- import java.security.cert.X509Certificate;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.TrustManager;
- import javax.net.ssl.X509TrustManager;
- import org.apache.http.conn.ssl.SSLSocketFactory;
- public class MySSLSocketFactory extends SSLSocketFactory {
- SSLContext sslContext = SSLContext.getInstance("TLS");
- public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
- super(truststore);
- TrustManager tm = new X509TrustManager() {
- public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- }
- public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
- }
- public X509Certificate[] getAcceptedIssuers() {
- return null;
- }
- };
- sslContext.init(null, new TrustManager[] { tm }, null);
- }
- @Override
- public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
- return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
- }
- @Override
- public Socket createSocket() throws IOException {
- return sslContext.getSocketFactory().createSocket();
- }
- }
类ClientUtil 获取可以支持https的HttpClient对象,调用 MySSLSocketFactory 来取得
[java]
view plain
copy
- import java.security.KeyStore;
- import org.apache.http.HttpVersion;
- import org.apache.http.client.HttpClient;
- import org.apache.http.conn.ClientConnectionManager;
- import org.apache.http.conn.scheme.PlainSocketFactory;
- import org.apache.http.conn.scheme.Scheme;
- import org.apache.http.conn.scheme.SchemeRegistry;
- import org.apache.http.conn.ssl.SSLSocketFactory;
- import org.apache.http.impl.client.DefaultHttpClient;
- import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
- import org.apache.http.params.BasicHttpParams;
- import org.apache.http.params.HttpParams;
- import org.apache.http.params.HttpProtocolParams;
- import org.apache.http.protocol.HTTP;
- public class ClientUtil {
- public static HttpClient getNewHttpClient() {
- try {
- KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
- trustStore.load(null, null);
- SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
- sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
- HttpParams params = new BasicHttpParams();
- HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
- HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
- SchemeRegistry registry = new SchemeRegistry();
- registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
- registry.register(new Scheme("https", sf, 443));
- ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
- return new DefaultHttpClient(ccm, params);
- } catch (Exception e) {
- e.printStackTrace();
- return new DefaultHttpClient();
- }
- }
- }
接下来就是调用JPush的api来推送消息了
[java]
view plain
copy
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.http.HttpEntity;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- /**
- * 调用远程api实现推送
- * @author naiyu
- *
- */
- public class PushMsgUtil {
- // public static final String PUSH_URL = "https://api.jpush.cn:443/sendmsg/sendmsg";
- public static final String PUSH_URL = "http://api.jpush.cn:8800/sendmsg/sendmsg";
- public static void pushMsg(String msg) {
- BasicNameValuePair name = new BasicNameValuePair("username", "test"); //用户名
- BasicNameValuePair sendno = new BasicNameValuePair("sendno", "3621"); // 发送编号。由开发者自己维护,标识一次发送请求
- BasicNameValuePair appkeys = new BasicNameValuePair("appkeys", "your appkeys"); // 待发送的应用程序(appKey),只能填一个。
- BasicNameValuePair receiver_type = new BasicNameValuePair("receiver_type", "4");
- //验证串,用于校验发送的合法性。
- BasicNameValuePair verification_code = new BasicNameValuePair("verification_code", getVerificationCode());
- //发送消息的类型:1 通知 2 自定义
- BasicNameValuePair msg_type = new BasicNameValuePair("msg_type", "1");
- BasicNameValuePair msg_content = new BasicNameValuePair("msg_content", msg);
- //目标用户终端手机的平台类型,如: android, ios 多个请使用逗号分隔。
- BasicNameValuePair platform = new BasicNameValuePair("platform", "android");
- List<BasicNameValuePair> datas = new ArrayList<BasicNameValuePair>();
- datas.add(name);
- datas.add(sendno);
- datas.add(appkeys);
- datas.add(receiver_type);
- datas.add(verification_code);
- datas.add(msg_type);
- datas.add(msg_content);
- datas.add(platform);
- try {
- HttpEntity entity = new UrlEncodedFormEntity(datas, "utf-8");
- HttpPost post = new HttpPost(PUSH_URL);
- post.setEntity(entity);
- HttpClient client = ClientUtil.getNewHttpClient();
- HttpResponse reponse = client.execute(post);
- HttpEntity resEntity = reponse.getEntity();
- System.out.println(EntityUtils.toString(resEntity));
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- }
- private static String getVerificationCode() {
- String username = "test"; //username 是开发者Portal帐户的登录帐户名
- String password = "pasword";
- int sendno = 3621;
- int receiverType = 4;
- String md5Password = StringUtils.toMD5(password);; //password 是开发者Portal帐户的登录密码
- String input = username + sendno + receiverType + md5Password;
- String verificationCode = StringUtils.toMD5(input);
- return verificationCode;
- }
- public static void main(String[] args) {
- String msg = "{\"n_title\":\"来点外卖\",\"n_content\":\"你好\"}";
- System.out.println(msg);
- PushMsgUtil.pushMsg(msg);
- }
- }
运行成功:
附上StringUtils,java
[java]
view plain
copy
- import java.security.MessageDigest;
- public class StringUtils {
- private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
- "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
- private static String byteArrayToHexString(byte[] b) {
- StringBuffer resultSb = new StringBuffer();
- for (int i = 0; i < b.length; i++) {
- resultSb.append(byteToHexString(b[i]));
- }
- return resultSb.toString();
- }
- private static String byteToHexString(byte b) {
- int n = b;
- if (n < 0)
- n = 256 + n;
- int d1 = n / 16;
- int d2 = n % 16;
- return hexDigits[d1] + hexDigits[d2];
- }
- public static String toMD5(String origin) {
- String resultString = null;
- try {
- resultString = new String(origin);
- MessageDigest md = MessageDigest.getInstance("MD5");
- resultString = byteArrayToHexString(md.digest(resultString
- .getBytes()));
- } catch (Exception ex) {
- ex.printStackTrace();
- }
- return resultString;
- }
- }