Free docking case of API interface for Zhongtong Express Logistics Single Query

Posted by someguyhere on Wed, 31 Jul 2019 19:12:47 +0200

Express inquiry API interface uses the logistics number to query the logistics information.Mainly used in e-commerce stores, ERP systems, WMS systems, express cabinets, banks and other enterprises.Several express logistics companies have unified interface access. It is recommended that docking interface providers can access more than one express at a time, which will save a lot of work in later technical maintenance.

At present, there are two ways to implement the API interface of courier query, one is active query, the other is subscription interface push data.Take the courier bird interface as an example (interface docking requires interface secret key, which is tested and cannot be used officially. You can apply to the courier bird website for http://www.kdniao.com/, which is a free secret key application). The last two methods are demo.

1. Active Query (Instant Query API)

1) Interface Rules

a. Query interface supports query by shipping bill number (single query, concurrent not more than 10/S).

b. Select the appropriate courier company code for the specified logistics waybill number, if the format is incorrect or if the code is incorrect, the failure information will be returned.For example, the express company code (ZTO) should be selected for the Zhongtong Express Logistics Number.

c. Logistics tracking information returned is sorted in ascending order according to the time of occurrence.

d. Interface instruction 1002.

e. Request address: Express bird

   
2) System-level and application-level input parameters

System-level input parameters

type

Application level input parameters

Must Require

Explain

RequestData

String

OrderCode

O

Order Number

Request content, JSON format, consistent with DataType

ShipperCode

R

Express company code

LogisticCode

R

Logistics Order Number

EBusinessID

String

 

R

E-commerce ID

RequestType

String

R

Request instruction type: 1002

DataSign

String

R

Data Content Signature

DataType

String

R

Request and return data type: 2-json;

3) Return result parameters
Parameter Name

type

Must Require

Explain

EBusinessID

String

R

E-commerce User ID

OrderCode

String

O

Order Number

ShipperCode

String

R

Express company code

LogisticCode

String

R

Logistics waybill number

CallBack

String

O

User ID

Success

Bool

R

Success or failure

Reason

String

O

Reasons for failure

State

String

R

Logistics Status: 0-Trackless 2-On-the-way, 3-Sign-in, 4-Problem

Traces/Logistics Track Details

AcceptTime

String

R

time

AcceptStation

String

R

describe

Remark

String

O

Remarks

4) Example JSON request
{

   "OrderCode": "",

   "ShipperCode": "SF",

   "LogisticCode": "118650888018"

}
// "SF" is coded by Shunfeng Express Company, other codes can be downloaded on the official website of Express Bird

5) JSON return example

//No Logistics Track

{

   "EBusinessID": "1109259",

    "Traces":[],

   "OrderCode": "",

   "ShipperCode": "SF",

   "LogisticCode": "118461988807",

   "Success": true,

   "Reason": null

}

//with logistics tracks

{

   "EBusinessID": "1109259",

    "OrderCode":"",

   "ShipperCode": "SF",

   "LogisticCode": "118461988807",

   "Success": true,

    "CallBack":"",

   "State": 3,

   "Reason": null,

    "Traces":[

        {

           "AcceptTime": "2014/06/25 08:05:37",

"AcceptStation": "Delivering." (Deliver: Dun Yufu, Phone: 18718866310) [Shenzhen]),

           "Remark": null

        },

        {

           "AcceptTime": "2014/06/25 04:01:28",

"AcceptStation": "Express at Shenzhen Distribution Center, ready for next stop in Shenzhen [Shenzhen]".

           "Remark": null

        },

        {

            "AcceptTime": "2014/06/2501:41:06",

"AcceptStation": "Express in Shenzhen Distribution Center [Shenzhen]"

           "Remark": null

        },

        {

           "AcceptTime": "2014/06/24 20:18:58",

"AcceptStation": "Received [Shenzhen]",

           "Remark": null

        },

        {

           "AcceptTime": "2014/06/24 20:55:28",

"AcceptStation": "Express in Shenzhen, ready for delivery to the next Shenzhen Distribution Center [Shenzhen]".

           "Remark": null

        },

        {

           "AcceptTime": "2014/06/25 10:23:03",

"AcceptStation": "Dispatch signed [Shenzhen]",

           "Remark": null

        },

        {

           "AcceptTime": "2014/06/25 10:23:03",

"AcceptStation": "Signed to: signed [Shenzhen]",

           "Remark": null

        }

    ]

}

Subscription Interface Push Data (Logistics Tracking API)

Subscription query interface is a customized service. Users can subscribe order information to the courier company. After the courier company updates its tracks, the real-time interface will be converted into a standard form, which will be pushed to the user to play the role of real-time pushing and improve efficiency.
At the same time, the data subscribed by the user can also choose whether to notify the courier to come to the door or not to place an order online.In addition, courier bird has other interface schemes such as on-the-way monitoring, electronic polygon sheets and so on, which can be selected according to the company's needs.

1) Interface Rules

a. Information received by the order (information distributed to the network, salesperson) will be pushed to the customer through the push interface (subscription concurrent no more than 30 times/S) the customer needs to implement the interface as required.

b. Only Json format is supported.

c. Request instruction 1008.

d. Test interface address: http://testapi.kdniao.cc:8081/api/dist

e. Change to the official address after the joint adjustment is passed: http://api.kdniao.cc/api/dist

f, Distribution and Subscription interfaces require the client to implement the callback interface, callback RequestType(1008)

2) System-level and application-level parameters

System-level input parameters

Application level input parameters

type

Is it necessary

describe

RequestData (required parameters, request content, JSON format, must match DataType)

CallBack

String

O

User-defined callback information

MemberID

String

O

Membership ID (alternate field)

WareHouseID

String

O

Warehouse identification (alternate fields)

CustomerName

String

O

Electronic form customer account

(with express site applications)

CustomerPwd

String

O

Electronic Face Single Password

SendSite

String

O

Recipient Point Identification

ShipperCode

String

R

Express company code

LogisticCode

String

R

Courier number

OrderCode

String

O

Order Number

MonthCode

String

O

Month-end code

PayType

Int

O

Postage payment method:

1-Cash, 2-Cash, 3-Month Closed, 4-Third Party Payment

ExpType

String

O

Express type: 1-Standard Express

Cost

Double

O

Shipping (Freight)

OtherCost

Double

O

Other expenses

Receiver

Company

String

O

Recipient Company

Name

String

O

Addressee

Tel

String

O

Telephone

Mobile

String

O

Mobile phone

PostCode

String

O

Recipient Zip Code

ProvinceName

String

O

Recipient Province (e.g. Guangdong Province, do not lack "Province")

CityName

String

O

Recipient City (e.g. Shenzhen, do not lack "City")

ExpAreaName

String

O

Recipient area (e.g. Futian area, do not lack "District" or "County")

Address

String

O

Recipient Detailed Address

Sender

Company

String

O

Sender Company

Name

String

O

Sender

Tel

String

O

Sender Phone

Mobile

String

O

Sender Mobile

PostCode

String

O

Sender Zip Code

ProvinceName

String

O

Sending Province (e.g. Guangdong Province, do not lack "Province")

CityName

String

O

Sending City (e.g. Shenzhen, do not lack "City")

ExpAreaName

String

O

Sending area (e.g. Futian area, do not lack "district" or "county")

Address

String

O

Send Detailed Address

StartDate

String

O

Home pick-up period:

"yyyy-MM-dd HH:mm:ss" format, all the time formats in this article are the same

EndDate

String

O

Weight

Double

O

Total weight of items kg

Quantity

Int

O

Number of Parcels/Parcels

Volume

Double

O

Total Item Volume m3

Remark

String

O

Remarks

IsNotice

Int

O

Whether to distribute to express companies: 1-No distribution; 0-Distribution. Default 0

IsSendMessage

Int

O

Whether to subscribe to SMS

0-No; 1-Need

AddService

Name

String


0

Value added service name

Value

String


0

Value-added service value

CustomerID

String


0

Customer ID (optional)

Commodity

GoodsName

String

O

Commodity Name

GoodsCode

String

O

Commodity Code

Goodsquantity

Int

O

Number

GoodsPrice

Double

O

commodity price

GoodsWeight

Double

O

Commodity weight kg

GoodsDesc

String

O

Commodity description

GoodsVol

Double

O

Commodity volume m3

EBusinessID

 

String

R

Merchant ID

RequestType

String

R

Request instruction type: 1008

DataSign

String

R

Data Content Signature

DataType

String

R

Request and return data type: 2-json;

3) Return result parameters

- Synchronous return

Parameter Name

type

Must Require

Explain

EBusinessID

String

R

E-commerce User ID

UpdateTime

String

R

time

Success

Bool

R

Success or failure: true,false

Reason

String

O

Reasons for failure

EstimatedDeliveryTime

String

O

Estimated order arrival time yyy-mm-dd

4) Example JSON request
{

    "ShipperCode":"SF",

   "OrderCode":"SF201608081055208281",

    "LogisticCode":"3100707578976",

    "PayType":"1",

    "ExpType":"1",

    "CustomerName":"",

    "CustomerPwd":"",

    "MonthCode":"",

    "IsNotice":"0",

    "Sender":{

        "Name":"1255760",

        "Tel":"",

       "Mobile":"13700000000",

ProvinceName: Guangdong Province,

CityName: "Shenzhen".

ExpAreaName: Fukuda District,

Address: "Test Address"

    },

    "Receiver":{

        "Name":"1255760",

        "Tel":"",

       "Mobile":"13800000000",

ProvinceName: Guangdong Province,

CityName: "Shenzhen".

ExpAreaName: "Longhua New Area".

Address: "Test Address 2"

    },

    "Commodity":[

        {

GoodsName: "Book"

        }

    ]

}

5) JSON return example

{

    "EBusinessID":"1151847",

    "UpdateTime": "2016-08-0916:42:38",

    "Success": true,

    "Reason": ""

    "EstimatedDeliveryTime":"2016-8-12"

}

Instant Query APIdemo

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/*

  • Express Bird Logistics Track Instant Query Interface
  • E-commerce ID s and private keys in DEMO are for testing purposes only. Register your account separately for formal environment
  • More than 500 inquiries per day, recommended access to our logistics track subscription push interface
  • ID and Key please go to the official website to apply: http://www.kdniao.com/ServiceApply.aspx
    */

public class KdniaoTrackQueryAPI {

//DEMO
public static void main(String[] args) {
    KdniaoTrackQueryAPI api = new KdniaoTrackQueryAPI();
    try {
        String result = api.getOrderTracesByJson("ANE", "210001633605");
        System.out.print(result);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//E-commerce ID
private String EBusinessID="Please apply to the Express Bird website http://www.kdniao.com/ServiceApply.aspx";
//E-commerce encryption private key, courier bird provided, take care to keep, do not leak
private String AppKey="Please apply to the Express Bird website http://www.kdniao.com/ServiceApply.aspx";
//Request url
private String ReqURL="http://api.kdniao.cc/Ebusiness/EbusinessOrderHandle.aspx";   

/**
 * Json Method Query Order Logistics Track
 * @throws Exception 
 */
public String getOrderTracesByJson(String expCode, String expNo) throws Exception{
    String requestData= "{'OrderCode':'','ShipperCode':'" + expCode + "','LogisticCode':'" + expNo + "'}";

    Map<String, String> params = new HashMap<String, String>();
    params.put("RequestData", urlEncoder(requestData, "UTF-8"));
    params.put("EBusinessID", EBusinessID);
    params.put("RequestType", "1002");
    String dataSign=encrypt(requestData, AppKey, "UTF-8");
    params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
    params.put("DataType", "2");

    String result=sendPost(ReqURL, params); 

    //Return information based on company business processes...

    return result;
}

/**
 * MD5 encryption
 * @param str content       
 * @param charset Encoding Method
 * @throws Exception 
 */
@SuppressWarnings("unused")
private String MD5(String str, String charset) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(str.getBytes(charset));
    byte[] result = md.digest();
    StringBuffer sb = new StringBuffer(32);
    for (int i = 0; i < result.length; i++) {
        int val = result[i] & 0xff;
        if (val <= 0xf) {
            sb.append("0");
        }
        sb.append(Integer.toHexString(val));
    }
    return sb.toString().toLowerCase();
}

/**
 * base64 Code
 * @param str content       
 * @param charset Encoding Method
 * @throws UnsupportedEncodingException 
 */
private String base64(String str, String charset) throws UnsupportedEncodingException{
    String encoded = base64Encode(str.getBytes(charset));
    return encoded;    
}   

@SuppressWarnings("unused")
private String urlEncoder(String str, String charset) throws UnsupportedEncodingException{
    String result = URLEncoder.encode(str, charset);
    return result;
}

/**
 * E-commerce Sign ature Generation
 * @param content content   
 * @param keyValue Appkey  
 * @param charset Encoding Method
 * @throws UnsupportedEncodingException ,Exception
 * @return DataSign autograph
 */
@SuppressWarnings("unused")
private String encrypt (String content, String keyValue, String charset) throws UnsupportedEncodingException, Exception
{
    if (keyValue != null)
    {
        return base64(MD5(content + keyValue, charset), charset);
    }
    return base64(MD5(content, charset), charset);
}

 /**
 * Send a request for a POST method to a specified URL     
 * @param url URL to send the request    
 * @param params Requested parameter set     
 * @return Response results from remote resources
 */
@SuppressWarnings("unused")
private String sendPost(String url, Map<String, String> params) {
    OutputStreamWriter out = null;
    BufferedReader in = null;        
    StringBuilder result = new StringBuilder(); 
    try {
        URL realUrl = new URL(url);
        HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection();
        // Sending a POST request must be set to two lines
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // POST Method
        conn.setRequestMethod("POST");
        // Setting common request properties
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.connect();
        // Gets the output stream corresponding to the URLConnection object
        out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        // Send Request Parameters            
        if (params != null) {
              StringBuilder param = new StringBuilder(); 
              for (Map.Entry<String, String> entry : params.entrySet()) {
                  if(param.length()>0){
                      param.append("&");
                  }               
                  param.append(entry.getKey());
                  param.append("=");
                  param.append(entry.getValue());                     
                  //System.out.println(entry.getKey()+":"+entry.getValue());
              }
              //System.out.println("param:"+param.toString());
              out.write(param.toString());
        }
        // Buffering of flush output stream
        out.flush();
        // Define the BufferedReader input stream to read the response of the URL
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
    } catch (Exception e) {            
        e.printStackTrace();
    }
    //Use finally blocks to close output and input streams
    finally{
        try{
            if(out!=null){
                out.close();
            }
            if(in!=null){
                in.close();
            }
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
    }
    return result.toString();
}

private static char[] base64EncodeChars = new char[] { 
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 
    'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 
    'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 
    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
    'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 
    'w', 'x', 'y', 'z', '0', '1', '2', '3', 
    '4', '5', '6', '7', '8', '9', '+', '/' }; 

public static String base64Encode(byte[] data) { 
    StringBuffer sb = new StringBuffer(); 
    int len = data.length; 
    int i = 0; 
    int b1, b2, b3; 
    while (i < len) { 
        b1 = data[i++] & 0xff; 
        if (i == len) 
        { 
            sb.append(base64EncodeChars[b1 >>> 2]); 
            sb.append(base64EncodeChars[(b1 & 0x3) << 4]); 
            sb.append("=="); 
            break; 
        } 
        b2 = data[i++] & 0xff; 
        if (i == len) 
        { 
            sb.append(base64EncodeChars[b1 >>> 2]); 
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); 
            sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); 
            sb.append("="); 
            break; 
        } 
        b3 = data[i++] & 0xff; 
        sb.append(base64EncodeChars[b1 >>> 2]); 
        sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); 
        sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]); 
        sb.append(base64EncodeChars[b3 & 0x3f]); 
    } 
    return sb.toString(); 
}

}

Logistics Tracking APIdemo

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.security.MessageDigest;

/*

public class KdniaoSubscribeAPI {

//DEMO
public static void main(String[] args) {
    KdniaoSubscribeAPI api = new KdniaoSubscribeAPI();
    try {
        String result = api.orderTracesSubByJson();
        System.out.print(result);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

//E-commerce ID
private String EBusinessID="Please apply to the Express Bird website http://www.kdniao.com/ServiceApply.aspx";
//E-commerce encryption private key, courier bird provided, take care to keep, do not leak
private String AppKey="Please apply to the Express Bird website http://www.kdniao.com/ServiceApply.aspx";
//Test request url
private String ReqURL = "http://testapi.kdniao.cc:8081/api/dist";
//Formal request url
//private String ReqURL = "http://api.kdniao.cc/api/dist";

/**
 * Json Mode Logistics Information Subscription
 * @throws Exception 
 */
public String orderTracesSubByJson() throws Exception{
    String requestData="{'OrderCode': 'SF201608081055208281'," +
                            "'ShipperCode':'SF'," +
                            "'LogisticCode':'3100707578976'," +
                            "'PayType':1," +
                            "'ExpType':1," +
                            "'CustomerName':'',"+
                            "'CustomerPwd':''," +
                            "'MonthCode':''," +
                            "'IsNotice':0," +
                            "'Cost':1.0," +
                            "'OtherCost':1.0," +
                            "'Sender':" +
                            "{" +
                            "'Company':'LV','Name':'Taylor','Mobile':'15018442396','ProvinceName':'Shanghai','CityName':'Shanghai','ExpAreaName':'Qingpu District','Address':'No. 73 Mingzhu Road'}," +
                            "'Receiver':" +
                            "{" +
                            "'Company':'GCCUI','Name':'Yann','Mobile':'15018442396','ProvinceName':'Beijing','CityName':'Beijing','ExpAreaName':'Chaoyang District','Address':'Yaxiu Building, Sanlitun Street'}," +
                            "'Commodity':" +
                            "[{" +
                            "'GoodsName':'shoes','Goodsquantity':1,'GoodsWeight':1.0}]," +
                            "'Weight':1.0," +
                            "'Quantity':1," +
                            "'Volume':0.0," +
                            "'Remark':'Handle with care'}";

    Map<String, String> params = new HashMap<String, String>();
    params.put("RequestData", urlEncoder(requestData, "UTF-8"));
    params.put("EBusinessID", EBusinessID);
    params.put("RequestType", "1008");
    String dataSign=encrypt(requestData, AppKey, "UTF-8");
    params.put("DataSign", urlEncoder(dataSign, "UTF-8"));
    params.put("DataType", "2");

    String result=sendPost(ReqURL, params); 

    //Return information based on company business processes...

    return result;
}

/**
 * MD5 encryption
 * @param str content       
 * @param charset Encoding Method
 * @throws Exception 
 */
@SuppressWarnings("unused")
private String MD5(String str, String charset) throws Exception {
    MessageDigest md = MessageDigest.getInstance("MD5");
    md.update(str.getBytes(charset));
    byte[] result = md.digest();
    StringBuffer sb = new StringBuffer(32);
    for (int i = 0; i < result.length; i++) {
        int val = result[i] & 0xff;
        if (val <= 0xf) {
            sb.append("0");
        }
        sb.append(Integer.toHexString(val));
    }
    return sb.toString().toLowerCase();
}

/**
 * base64 Code
 * @param str content       
 * @param charset Encoding Method
 * @throws UnsupportedEncodingException 
 */
private String base64(String str, String charset) throws UnsupportedEncodingException{
    String encoded = base64Encode(str.getBytes(charset));
    return encoded;    
}   

@SuppressWarnings("unused")
private String urlEncoder(String str, String charset) throws UnsupportedEncodingException{
    String result = URLEncoder.encode(str, charset);
    return result;
}

/**
 * E-commerce Sign ature Generation
 * @param content content   
 * @param keyValue Appkey  
 * @param charset Encoding Method
 * @throws UnsupportedEncodingException ,Exception
 * @return DataSign autograph
 */
@SuppressWarnings("unused")
private String encrypt (String content, String keyValue, String charset) throws UnsupportedEncodingException, Exception
{
    if (keyValue != null)
    {
        return base64(MD5(content + keyValue, charset), charset);
    }
    return base64(MD5(content, charset), charset);
}

 /**
 * Send a request for a POST method to a specified URL     
 * @param url URL to send the request    
 * @param params Requested parameter set     
 * @return Response results from remote resources
 */
@SuppressWarnings("unused")
private String sendPost(String url, Map<String, String> params) {
    OutputStreamWriter out = null;
    BufferedReader in = null;        
    StringBuilder result = new StringBuilder(); 
    try {
        URL realUrl = new URL(url);
        HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection();
        // Sending a POST request must be set to two lines
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // POST Method
        conn.setRequestMethod("POST");
        // Setting common request properties
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.connect();
        // Gets the output stream corresponding to the URLConnection object
        out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
        // Send Request Parameters            
        if (params != null) {
              StringBuilder param = new StringBuilder(); 
              for (Map.Entry<String, String> entry : params.entrySet()) {
                  if(param.length()>0){
                      param.append("&");
                  }               
                  param.append(entry.getKey());
                  param.append("=");
                  param.append(entry.getValue());                     
                  System.out.println(entry.getKey()+":"+entry.getValue());
              }
              System.out.println("param:"+param.toString());
              out.write(param.toString());
        }
        // Buffering of flush output stream
        out.flush();
        // Define the BufferedReader input stream to read the response of the URL
        in = new BufferedReader(
                new InputStreamReader(conn.getInputStream(), "UTF-8"));
        String line;
        while ((line = in.readLine()) != null) {
            result.append(line);
        }
    } catch (Exception e) {            
        e.printStackTrace();
    }
    //Use finally blocks to close output and input streams
    finally{
        try{
            if(out!=null){
                out.close();
            }
            if(in!=null){
                in.close();
            }
        }
        catch(IOException ex){
            ex.printStackTrace();
        }
    }
    return result.toString();
}

private static char[] base64EncodeChars = new char[] { 
        'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 
        'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 
        'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 
        'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 
        'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 
        'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 
        'w', 'x', 'y', 'z', '0', '1', '2', '3', 
        '4', '5', '6', '7', '8', '9', '+', '/' }; 

public static String base64Encode(byte[] data) { 
    StringBuffer sb = new StringBuffer(); 
    int len = data.length; 
    int i = 0; 
    int b1, b2, b3; 
    while (i < len) { 
        b1 = data[i++] & 0xff; 
        if (i == len) 
        { 
            sb.append(base64EncodeChars[b1 >>> 2]); 
            sb.append(base64EncodeChars[(b1 & 0x3) << 4]); 
            sb.append("=="); 
            break; 
        } 
        b2 = data[i++] & 0xff; 
        if (i == len) 
        { 
            sb.append(base64EncodeChars[b1 >>> 2]); 
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); 
            sb.append(base64EncodeChars[(b2 & 0x0f) << 2]); 
            sb.append("="); 
            break; 
        } 
        b3 = data[i++] & 0xff; 
        sb.append(base64EncodeChars[b1 >>> 2]); 
        sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]); 
        sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]); 
        sb.append(base64EncodeChars[b3 & 0x3f]); 
    } 
    return sb.toString(); 
}

}

Topics: Programming Java JSON Mobile encoding