Java Remote Call of jpush Aurora push API

Source: Internet
Author: User
Tags sendmsg

The jpush API has been called in detail on the official website. Here we mainly describe the problems I encountered during the call process,

For example

My httpclient does not support HTTPS requests,

Parameter configuration error and verification error.

When the development needs to reference appache package commons-httpclient.jar, commons-codec.jar, commons-logging.jar these packages can be downloaded on the official website, if you need, I can also send to you.

After these packages are introduced, you can develop them.

Here, we need to note the following two points:

1. Use httpclient client = new defaulthttpclient (); obtain httpclient objects that do not support HTTPS and must be rewritten by yourself.

2. Our MD5 code is the same as that on the server. (When I used my own MD5 code for verification, the verification always failed. Later I asked their technical staff for their MD5 implementation method and passed the verification)

Well, I don't need to talk much about it. The next step is to paste the Code:

Use mysslsocketfactory to support https

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();      }  }

Class clientutil to obtain httpclient objects that support https, and call mysslsocketfactory to obtain

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();      }  }}

Next, call the jpush API to push messages.

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;/*** call Remote API to implement push * @ author naiyu **/Public C Lass pushmsgutil {// public static final string push_url = "https://api.jpush.cn: 443/sendmsg"; public static final string push_url = "http://api.jpush.cn: 8800/sendmsg "; public static void pushmsg (string MSG) {basicnamevaluepair name = new basicnamevaluepair ("username", "test"); // username basicnamevaluepair sendno = new principal ("sendno ", "3621"); // The sender id. Maintained by the developer, it identifies one send request basicnamevaluepair appkeys = new basicnamevaluepair ("appkeys", "Your appkeys"); // The application to be sent (appkey), which can only be filled in. Basicnamevaluepair receiver_type = new basicnamevaluepair ("receiver_type", "4"); // verification string, used to verify the validity of the sent message. Required verification_code = new response ("verification_code", getverificationcode (); // message sending type: 1 Notification 2 custom basicnamevaluepair msg_type = new basicnamevaluepair ("msg_type ", "1"); basicnamevaluepair msg_content = new basicnamevaluepair ("msg_content", MSG); // platform type of the target user's terminal mobile phone, such as Android and iOS. Use commas to separate multiple platforms. 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.exe cute (post); httpentity resentity = reponse. getentity (); system. out. println (entityutils. tostring (resentity);} catch (exception ex) {ex. printstacktrace () ;}} Private Static string getverificationcode () {string username = "test"; // username is the Logon account name of the developer portal account string Password = "pasword "; int sendno= 3621; int receivertype = 4; string md5password = stringutils. tomd5 (password); // password is the logon password of the developer portal account string input = username + sendno + receivertype + md5password; string verificationcode = stringutils. tomd5 (input); Return verificationcode;} public static void main (string [] ARGs) {string MSG = "{\" n_title \ ": \" order takeout \", \ "n_content \": \ "Hello \"} "; system. out. println (MSG); pushmsgutil. pushmsg (MSG );}}

Run successfully:

Attached stringutils, Java

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;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.