JPush极光推送的android实现

这里需要特别说明的两点是:

1、通过 HttpClient client = new DefaultHttpClient(); 获得HttpClient对象不支持https,需要自己重写。

2、我们的MD5编码要和服务器那边的一样。(我用我自己写的MD5编码验证的时候,总是验证失败,后来跟他们的技术人员要了他们的md5的实现方式就通过验证了)


好了,废话不多说了,接下来是贴代码的时候了:

类MySSLSocketFactory用来实现对https的支持

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.io.IOException;  
  2. import java.net.Socket;  
  3. import java.net.UnknownHostException;  
  4. import java.security.KeyManagementException;  
  5. import java.security.KeyStore;  
  6. import java.security.KeyStoreException;  
  7. import java.security.NoSuchAlgorithmException;  
  8. import java.security.UnrecoverableKeyException;  
  9. import java.security.cert.CertificateException;  
  10. import java.security.cert.X509Certificate;  
  11.   
  12. import javax.net.ssl.SSLContext;  
  13. import javax.net.ssl.TrustManager;  
  14. import javax.net.ssl.X509TrustManager;  
  15.   
  16. import org.apache.http.conn.ssl.SSLSocketFactory;  
  17.   
  18. public class MySSLSocketFactory extends SSLSocketFactory {  
  19.   
  20.         SSLContext sslContext = SSLContext.getInstance("TLS");    
  21.         
  22.         public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {    
  23.             super(truststore);    
  24.         
  25.             TrustManager tm = new X509TrustManager() {    
  26.                 public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {    
  27.                 }    
  28.         
  29.                 public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {    
  30.                 }    
  31.         
  32.                 public X509Certificate[] getAcceptedIssuers() {    
  33.                     return null;    
  34.                 }    
  35.             };    
  36.         
  37.             sslContext.init(nullnew TrustManager[] { tm }, null);    
  38.         }    
  39.         
  40.         @Override    
  41.         public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {    
  42.             return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);    
  43.         }    
  44.         
  45.         @Override    
  46.         public Socket createSocket() throws IOException {    
  47.             return sslContext.getSocketFactory().createSocket();    
  48.         }    
  49.   
  50. }  

类ClientUtil 获取可以支持https的HttpClient对象,调用 MySSLSocketFactory   来取得

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.security.KeyStore;  
  2.   
  3. import org.apache.http.HttpVersion;  
  4. import org.apache.http.client.HttpClient;  
  5. import org.apache.http.conn.ClientConnectionManager;  
  6. import org.apache.http.conn.scheme.PlainSocketFactory;  
  7. import org.apache.http.conn.scheme.Scheme;  
  8. import org.apache.http.conn.scheme.SchemeRegistry;  
  9. import org.apache.http.conn.ssl.SSLSocketFactory;  
  10. import org.apache.http.impl.client.DefaultHttpClient;  
  11. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;  
  12. import org.apache.http.params.BasicHttpParams;  
  13. import org.apache.http.params.HttpParams;  
  14. import org.apache.http.params.HttpProtocolParams;  
  15. import org.apache.http.protocol.HTTP;  
  16. public class ClientUtil {  
  17.       
  18.     public static HttpClient getNewHttpClient() {  
  19.          try {    
  20.                 KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());    
  21.                 trustStore.load(nullnull);    
  22.             
  23.                 SSLSocketFactory sf = new MySSLSocketFactory(trustStore);    
  24.                 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);    
  25.             
  26.                 HttpParams params = new BasicHttpParams();    
  27.                 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);    
  28.                 HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);    
  29.             
  30.                 SchemeRegistry registry = new SchemeRegistry();    
  31.                 registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));    
  32.                 registry.register(new Scheme("https", sf, 443));    
  33.             
  34.                 ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);    
  35.             
  36.                 return new DefaultHttpClient(ccm, params);    
  37.             } catch (Exception e) {  
  38.                 e.printStackTrace();  
  39.                 return new DefaultHttpClient();    
  40.             }    
  41.     }  
  42.   
  43. }  

接下来就是调用JPush的api来推送消息了

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.util.ArrayList;  
  2. import java.util.List;  
  3.   
  4. import org.apache.http.HttpEntity;  
  5. import org.apache.http.HttpResponse;  
  6. import org.apache.http.client.HttpClient;  
  7. import org.apache.http.client.entity.UrlEncodedFormEntity;  
  8. import org.apache.http.client.methods.HttpPost;  
  9. import org.apache.http.message.BasicNameValuePair;  
  10. import org.apache.http.util.EntityUtils;  
  11.   
  12. /** 
  13.  * 调用远程api实现推送 
  14.  * @author naiyu 
  15.  * 
  16.  */  
  17. public class PushMsgUtil {  
  18.       
  19. //  public static final String PUSH_URL = "https://api.jpush.cn:443/sendmsg/sendmsg";  
  20.     public static final String PUSH_URL = "http://api.jpush.cn:8800/sendmsg/sendmsg";  
  21.       
  22.     public static void pushMsg(String msg) {  
  23.         BasicNameValuePair name = new BasicNameValuePair("username""test");  //用户名  
  24.         BasicNameValuePair sendno = new BasicNameValuePair("sendno""3621");  // 发送编号。由开发者自己维护,标识一次发送请求  
  25.         BasicNameValuePair appkeys = new BasicNameValuePair("appkeys""your appkeys");  // 待发送的应用程序(appKey),只能填一个。  
  26.         BasicNameValuePair receiver_type = new BasicNameValuePair("receiver_type""4");    
  27.         //验证串,用于校验发送的合法性。  
  28.         BasicNameValuePair verification_code = new BasicNameValuePair("verification_code", getVerificationCode());  
  29.         //发送消息的类型:1 通知 2 自定义  
  30.         BasicNameValuePair msg_type = new BasicNameValuePair("msg_type""1");  
  31.         BasicNameValuePair msg_content = new BasicNameValuePair("msg_content", msg);  
  32.         //目标用户终端手机的平台类型,如: android, ios 多个请使用逗号分隔。  
  33.         BasicNameValuePair platform = new BasicNameValuePair("platform""android");  
  34.         List<BasicNameValuePair> datas = new ArrayList<BasicNameValuePair>();  
  35.         datas.add(name);  
  36.         datas.add(sendno);  
  37.         datas.add(appkeys);  
  38.         datas.add(receiver_type);  
  39.         datas.add(verification_code);  
  40.         datas.add(msg_type);  
  41.         datas.add(msg_content);  
  42.         datas.add(platform);  
  43.         try {  
  44.             HttpEntity entity = new UrlEncodedFormEntity(datas, "utf-8");  
  45.             HttpPost post = new HttpPost(PUSH_URL);  
  46.             post.setEntity(entity);  
  47.             HttpClient client = ClientUtil.getNewHttpClient();  
  48.             HttpResponse reponse = client.execute(post);  
  49.             HttpEntity resEntity = reponse.getEntity();  
  50.             System.out.println(EntityUtils.toString(resEntity));  
  51.         } catch (Exception ex) {  
  52.             ex.printStackTrace();  
  53.         }  
  54.           
  55.     }  
  56.       
  57.       
  58.     private static String getVerificationCode() {  
  59.   
  60.         String username = "test";  //username 是开发者Portal帐户的登录帐户名  
  61.         String password = "pasword";  
  62.         int sendno = 3621;  
  63.         int receiverType = 4;  
  64.         String md5Password = StringUtils.toMD5(password);; //password 是开发者Portal帐户的登录密码  
  65.            
  66.         String input = username + sendno + receiverType + md5Password;  
  67.         String verificationCode = StringUtils.toMD5(input);  
  68.         return verificationCode;  
  69.     }  
  70.       
  71.     public static void main(String[] args) {  
  72.         String msg = "{\"n_title\":\"来点外卖\",\"n_content\":\"你好\"}";  
  73.         System.out.println(msg);  
  74.         PushMsgUtil.pushMsg(msg);  
  75.     }  
  76.   
  77. }  


运行成功:




附上StringUtils,java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. import java.security.MessageDigest;  
  2.   
  3. public class StringUtils {  
  4.     private final static String[] hexDigits = { "0""1""2""3""4""5",  
  5.             "6""7""8""9""A""B""C""D""E""F" };  
  6.   
  7.     private static String byteArrayToHexString(byte[] b) {  
  8.         StringBuffer resultSb = new StringBuffer();  
  9.         for (int i = 0; i < b.length; i++) {  
  10.             resultSb.append(byteToHexString(b[i]));  
  11.         }  
  12.         return resultSb.toString();  
  13.     }  
  14.   
  15.     private static String byteToHexString(byte b) {  
  16.         int n = b;  
  17.         if (n < 0)  
  18.             n = 256 + n;  
  19.         int d1 = n / 16;  
  20.         int d2 = n % 16;  
  21.         return hexDigits[d1] + hexDigits[d2];  
  22.     }  
  23.   
  24.     public static String toMD5(String origin) {  
  25.         String resultString = null;  
  26.         try {  
  27.             resultString = new String(origin);  
  28.             MessageDigest md = MessageDigest.getInstance("MD5");  
  29.             resultString = byteArrayToHexString(md.digest(resultString  
  30.                     .getBytes()));  
  31.         } catch (Exception ex) {  
  32.             ex.printStackTrace();  
  33.         }  
  34.         return resultString;  
  35.     }  
  36. }  

猜你喜欢

转载自blog.csdn.net/larryluoshuai/article/details/54972390