com.weibo.net.Weibo.java Source code

Java tutorial

Introduction

Here is the source code for com.weibo.net.Weibo.java

Source

/*
 * Copyright 2011 Sina.
 *
 * Licensed under the Apache License and Weibo License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.open.weibo.com
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.weibo.net;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import weibo.data.Comment;
import weibo.data.Count;
import weibo.data.Status;
import weibo.data.StatusCounts;
import weibo.data.User;
import weibo.extension.OAuthConstant;
import android.text.TextUtils;
import android.util.Log;

/**
 * Encapsulation main Weibo APIs, Include: 1. getRquestToken , 2. getAccessToken, 3. url request.
 * Used as a single instance class. Implements a weibo api as a synchronized way.
 *
 * @author  ZhangJie (zhangjie2@staff.sina.com.cn)
 * @extend_by pcodezui@gmail.com
 */
public class Weibo {
    private static Map<String, SimpleDateFormat> formatMap = new HashMap<String, SimpleDateFormat>();
    public static String SERVER = "http://api.t.sina.com.cn/";
    public static String URL_OAUTH_TOKEN = "http://api.t.sina.com.cn/oauth/request_token";
    public static String URL_AUTHORIZE = "http://api.t.sina.com.cn/oauth/authorize";
    public static String URL_ACCESS_TOKEN = "http://api.t.sina.com.cn/oauth/access_token";
    public static String URL_AUTHENTICATION = "http://api.t.sina.com.cn/oauth/authenticate";

    //   public static String APP_KEY = "837378871";
    //   public static String APP_SECRET = "eead7b50ef53f056daf08996d0ccabb9";   
    public static String APP_KEY = "1862225408";
    public static String APP_SECRET = "f05af82fa8b8ec3d4b2715df875ed1cb";

    private static Weibo mWeiboInstance = null;
    private AccessToken mAccessToken = null;
    private RequestToken mRequestToken = null;
    private static Boolean netWorkIsError = false;

    private Weibo() {
        Utility.setRequestHeader("Accept-Encoding", "gzip");
        //      Utility.setTokenObject(this.mRequestToken);
    }

    public static Weibo getInstance() {
        if (mWeiboInstance == null) {
            mWeiboInstance = new Weibo();
        }
        return mWeiboInstance;
    }

    //accessToken
    public void setAccessToken(AccessToken token) {
        mAccessToken = token;
    }

    public AccessToken getAccessToken() {
        return this.mAccessToken;
    }

    public void setupConsumerConfig(String consumer_key, String consumer_secret) {
        Weibo.APP_KEY = consumer_key;
        Weibo.APP_SECRET = consumer_secret;
    }

    public void setRequestToken(RequestToken token) {
        this.mRequestToken = token;
    }

    //oauth_verifier
    public void addOauthverifier(String verifier) {
        mRequestToken.setVerifier(verifier);
    }

    /**
     * Requst sina weibo open api by get or post
     *
     * @param url
     *            Openapi request URL.
     * @param params
     *            http get or post parameters . e.g. gettimeling?max=max_id&min=min_id
     *            max and max_id is a pair of key and value for params, also the min and min_id
     * @param httpMethod
     *            http verb: e.g. "GET", "POST", "DELETE" 
     * @throws IOException 
     * @throws MalformedURLException 
     * @throws WeiboException 
     */
    public synchronized String request(String url, WeiboParameters params, String httpMethod, AccessToken token) {
        Utility.setAuthorization(new RequestHeader());
        String rlt = null;
        while (rlt == null) {
            try {
                rlt = Utility.openUrl(url, httpMethod, params, token);
            } catch (WeiboException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e("Erro", "!");
                setNetWorkIsError(true);
            }
        }
        setNetWorkIsError(false);
        return rlt;
    }

    /**/
    public RequestToken getRequestToken(String callback_url) throws WeiboException {
        Utility.setAuthorization(new RequestTokenHeader());
        WeiboParameters postParams = new WeiboParameters();
        postParams.add("oauth_callback", callback_url);
        String rlt;
        rlt = Utility.openUrl(Weibo.URL_OAUTH_TOKEN, "POST", postParams, null);
        RequestToken request = new RequestToken(rlt);
        this.mRequestToken = request;
        Log.e("requestToken_0", rlt);
        return request;
    }

    public AccessToken generateAccessToken() throws WeiboException {
        Utility.setAuthorization(new AccessTokenHeader());
        WeiboParameters authParam = new WeiboParameters();
        final long timestamp = System.currentTimeMillis() / 1000;
        final long nonce = timestamp + (new Random()).nextInt();

        //      authParam.add("oauth_consumer_key", APP_KEY);
        //      authParam.add("oauth_token", this.mRequestToken.getToken()); 
        //      authParam.add("oauth_token_secret", this.mRequestToken.getSecret()); 
        //      authParam.add("oauth_nonce", String.valueOf(nonce));
        //      authParam.add("oauth_timestamp", String.valueOf(timestamp));
        //    authParam.add("oauth_verifier", this.mRequestToken.getVerifier()/*"605835"*/); 
        //      authParam.add("oauth_verifier", this.mRequestToken.getVerifier());
        //      authParam.add("oauth_signature", HttpHeaderFactory.CONST_HMAC_SHA1);
        //      authParam.add("oauth_version", HttpHeaderFactory.CONST_OAUTH_VERSION);

        authParam.add("oauth_verifier", this.mRequestToken.getVerifier());
        authParam.add("source", APP_KEY);

        String rlt = Utility.openUrl(Weibo.URL_ACCESS_TOKEN, "POST", authParam, this.mRequestToken);
        AccessToken accessToken = new AccessToken(rlt);
        this.mAccessToken = accessToken;
        return accessToken;
    }

    public AccessToken getXauthAccessToken(String app_key, String app_secret, String usrname, String password)
            throws WeiboException {
        Utility.setAuthorization(new XAuthHeader());
        WeiboParameters postParams = new WeiboParameters();
        postParams.add("x_auth_username", usrname);
        postParams.add("x_auth_password", password);
        postParams.add("oauth_consumer_key", APP_KEY);
        String rlt = Utility.openUrl(Weibo.URL_ACCESS_TOKEN, "POST", postParams, null);
        AccessToken accessToken = new AccessToken(rlt);
        this.mAccessToken = accessToken;
        return accessToken;
    }

    private List<Comment> getComments(String content) throws WeiboException {
        List<Comment> comments = new ArrayList<Comment>();
        try {
            JSONArray jarray = new JSONArray(content);
            for (int i = 0; i < jarray.length(); i++) {
                Comment comment = new Comment();
                JSONObject json = jarray.getJSONObject(i);
                comment.setCreated_at(new Date(json.getString("created_at")));
                //            comment.setFavorited(json.getBoolean("favorited"));
                comment.setId(json.getLong("id"));
                //             comment.setSource(json.getString("source"));    
                //             comment.setStatus((Status) json.get("retweeted_status"));

                comment.setStatus(getStatus(json.getString("status")));

                comment.setText(json.getString("text"));
                //             comment.setTruncated(json.getBoolean("truncated"));
                //             comment.setUser((User) json.get("user"));

                //               Log.e("Weibo_comment user",  "Is NULL??");
                if (!json.isNull("user")) {
                    //                  Log.e("Weibo",  "User is not null");
                    String user_rlt = json.getString("user");
                    User user = getUser(user_rlt);
                    comment.setUser(user);
                    //                  Log.e("ScreenName", user.getScreen_name());
                }

                comments.add(comment); //Add in List<>
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return comments;
    }

    /**
     *  
     */
    public List<Comment> getCommentToMe(Long since_id, Long max_id, int count, int page) throws WeiboException {
        String content = commentsToMe(this, APP_KEY, since_id, max_id, count, page);
        return getComments(content);
    }

    private String commentsToMe(Weibo weibo, String source, Long since_id, Long max_id, int count, int page)
            throws WeiboException {

        WeiboParameters bundle = new WeiboParameters();
        if (since_id != null)
            bundle.add("since_id", since_id + "");
        if (max_id != null)
            bundle.add("max_id", max_id + "");
        if (count != -1)
            bundle.add("count", count + "");
        if (page != -1)
            bundle.add("page", page + "");
        bundle.add("source", APP_KEY);

        String url = Weibo.SERVER + "statuses/comments_to_me.json";

        Log.e("Operation:", "Will use request methd!");
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());

        return rlt;
    }

    /**
     *
     */
    public List<Comment> getCommentsByMe(Long since_id, Long max_id, int count, int page) throws WeiboException {
        String content = commentByMe(this, APP_KEY, since_id, max_id, count, page);
        return getComments(content);
    }

    /**
     *  
     */
    private String commentByMe(Weibo weibo, String source, Long since_id, Long max_id, int count, int page)
            throws WeiboException {

        WeiboParameters bundle = new WeiboParameters();
        if (since_id != null)
            bundle.add("since_id", since_id + "");
        if (max_id != null)
            bundle.add("max_id", max_id + "");
        bundle.add("count", count + "");
        bundle.add("page", page + "");
        bundle.add("source", Weibo.APP_KEY);

        String url = Weibo.SERVER + "statuses/comments_by_me.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     * statuses/comments ID 
     * @param id   ID 
     * @param count 20200    
     * @param page  1    
     */
    public List<Comment> getComments(Long id, int count, int page) throws WeiboException {
        String content = comments(this, APP_KEY, id, count, page);
        return getComments(content);
    }

    private String comments(Weibo weibo, String source, Long id, int count, int page) throws WeiboException {
        // TODO Auto-generated method stub
        WeiboParameters bundle = new WeiboParameters();
        if (id != null)
            bundle.add("since_id", id + "");
        bundle.add("count", count + "");
        bundle.add("page", page + "");
        bundle.add("source", Weibo.APP_KEY);

        String url = Weibo.SERVER + "statuses/comments.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    //====Status=================================================================
    /**
     *  
     * JSON  status
     * @throws WeiboException 
     */
    private List<Status> getStatusList(String content) throws WeiboException {
        List<Status> statuses = new ArrayList<Status>();
        try {
            //       content = publicTimeline(weibo, Weibo.APP_KEY, since_id, max_id, count, base_app);
            JSONArray jarray = new JSONArray(content);
            for (int i = 0; i < jarray.length(); i++) { //
                Status status = new Status();
                JSONObject json = jarray.getJSONObject(i);
                //             status.setBmiddle_pic(json.getString("bmiddle_pic"));
                status.setCreated_at(new Date(json.getString("created_at")));
                status.setFavorited(json.getBoolean("favorited"));
                status.setId(json.getLong("id"));
                //Long  String
                if (!json.isNull("in_reply_to_screen_name"))
                    status.setIn_reply_to_screen_name(json.getString("in_reply_to_screen_name"));
                else
                    status.setIn_reply_to_screen_name(json.getString(null));

                if (!json.isNull("in_reply_to_status_id"))
                    status.setIn_reply_to_status_id(json.getString("in_reply_to_status_id"));
                else
                    status.setIn_reply_to_status_id(json.getString(null));

                if (!json.isNull("in_reply_to_user_id"))
                    status.setIn_reply_to_user_id(json.getString("in_reply_to_user_id"));
                else
                    status.setIn_reply_to_user_id(json.getString(null));

                //             status.setOriginal_pic(json.getString("original_pic"));
                status.setSource(json.getString("source"));
                //             status.setRetweetedStatus((Status) json.get("retweeted_status"));
                if (!json.isNull("retweeted_status")) {
                    String retweeted_rlt = json.getString("retweeted_status");
                    Status retweeted_status = getStatus(retweeted_rlt);
                    status.setRetweetedStatus(retweeted_status);
                }

                status.setText(json.getString("text"));
                //             status.setThumbnail_pic(json.getString("thumbnail_pic"));
                status.setTruncated(json.getBoolean("truncated"));
                //             status.setUser((User) json.get("user"));
                if (!json.isNull("user")) {
                    String user_rlt = json.getString("user");
                    User user = getUser(user_rlt);
                    status.setUser(user);
                }

                statuses.add(status); //Add in List<>
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return statuses;
    }

    /**
     *   JSON  status
     * @throws WeiboException 
     */
    private Status getStatus(String content) throws WeiboException {
        Status status = new Status();

        try {
            JSONObject json = new JSONObject(content);
            //         status.setBmiddle_pic(json.getString("bmiddle_pic"));

            int length = content.split(":").length;
            for (int i = 0; i < length; i++) {
                //            Log.e("getStatus", 
                //                  content.split(":")[i]);

            }
            status.setCreated_at(new Date(json.getString("created_at")));
            status.setFavorited(json.getBoolean("favorited"));
            status.setId(json.getLong("id"));
            status.setIn_reply_to_screen_name(json.getString("in_reply_to_screen_name"));
            status.setIn_reply_to_status_id(json.getString("in_reply_to_status_id"));
            status.setIn_reply_to_user_id(json.getString("in_reply_to_user_id"));

            //         Log.e("original_pic", json.getString("original_pic"));
            if (!json.isNull("thumbnail_pic")) {
                status.setOriginal_pic(json.getString("original_pic"));
                status.setThumbnail_pic(json.getString("thumbnail_pic"));
                status.setBmiddle_pic(json.getString("bmiddle_pic"));
            }

            status.setSource(json.getString("source"));

            status.setText(json.getString("text"));
            //         
            //         Log.e("thumbnail_pic", json.getString("thumbnail_pic"));

            status.setTruncated(json.getBoolean("truncated"));
            //         

            if (!json.isNull("retweeted_status")) {
                String retweeted_rlt = json.getString("retweeted_status");
                Status retweeted_status = getStatus(retweeted_rlt);
                status.setRetweetedStatus(retweeted_status);
            }
            //         status.setUser((User) json.get("user")); 
            String user_rlt = json.getString("user");
            if (user_rlt != null && user_rlt != "") {
                User user = getUser(user_rlt);
                status.setUser(user);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return status;
    }

    /**     
     * @param since_id   ID
     * @param max_id         ID
     * @param count   
     * @param page  -1 
     * @param base_app 01
     */
    public List<Status> getPublicTimeline(int count, int base_app) throws WeiboException {
        String content = publicTimeline(this, Weibo.APP_KEY, count, base_app);
        return getStatusList(content);
    }

    private String publicTimeline(Weibo weibo, String source, int count, int base_app) throws WeiboException {
        // TODO Auto-generated method stub
        WeiboParameters bundle = new WeiboParameters();

        bundle.add("source", Weibo.APP_KEY);
        if (base_app != -1)
            bundle.add("base_app", base_app + "");
        if (count != -1)
            bundle.add("count", count + "");

        String url = Weibo.SERVER + "statuses/public_timeline.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     *   
     * @param count   -1  20200 
     * @param page    -1  
     */
    public List<Status> getFriendTimeLine(Long since_id, Long max_id, int count, int page) throws WeiboException {
        String content = friendTimeline(this, Weibo.APP_KEY, since_id, max_id, count, page);
        return getStatusList(content);
    }

    private String friendTimeline(Weibo weibo, String source, Long since_id, Long max_id, int count, int page)
            throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", Weibo.APP_KEY);
        if (since_id != null)
            bundle.add("since_id", since_id + "");
        if (max_id != null)
            bundle.add("max_id", max_id + "");
        if (count != -1)
            bundle.add("count", count + "");
        if (page != -1)
            bundle.add("page", page + "");

        String url = Weibo.SERVER + "statuses/friends_timeline.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     *  <br>
     *  :iduser_idscreen_name
     *  
     * @param id UID ID(int64)(string)
     * REST
     * @param user_id 
     * @param screen_name    UID
     * 
     * @param since_id IDsince_idsince_id
     * @param max_id   IDmax_id
     * @param count -1  20200   
     * @param page -1 1200
     * @param base_app  10
     * @param feature 
     * 01234.  
     */
    public List<Status> getUserTimeLine(String id, Long user_id, String screen_name, Long since_id, Long max_id,
            int count, int page, int base_APP_KEY, int feature) throws WeiboException {
        String content = user_timeline(this, id, user_id, screen_name, since_id, max_id, count, page, base_APP_KEY,
                feature);
        return getStatusList(content);
    }

    private String user_timeline(Weibo weibo, String id, Long user_id, String screen_name, Long since_id,
            Long max_id, int count, int page, int base_app, int feature) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", Weibo.APP_KEY);
        if (since_id != null)
            bundle.add("since_id", since_id + "");
        if (max_id != null)
            bundle.add("max_id", max_id + "");
        if (count != -1)
            bundle.add("count", count + "");
        if (page != -1)
            bundle.add("page", page + "");
        if (screen_name != null)
            bundle.add("screen_name", screen_name);
        if (base_app != -1)
            bundle.add("base_app", base_app + "");
        if (feature != -1)
            bundle.add("feature", feature + "");

        String url = Weibo.SERVER;
        if (id == null)
            url = url + "statuses/user_timeline.json";
        else
            url = url + "statuses/user_timeline/" + id + ".json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     * N  repost timeline
     * @param id  <ID>   
     * @param since_id null IDsince_idsince_id
     * @param max_id IDmax_id  null
     * @param count 20 200  -1
     * @param page      defualt 1
     * @throws WeiboException 
     */
    public List<Status> getRepostTimeline(Long id, Long since_id, Long max_id, int count, int page)
            throws WeiboException {
        String content = repost_timeline(this, id, since_id, max_id, count, page);
        return getStatusList(content);
    }

    private String repost_timeline(Weibo weibo, Long id, Long since_id, Long max_id, int count, int page)
            throws WeiboException {
        // TODO Auto-generated method stub
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", Weibo.APP_KEY);
        if (since_id != null)
            bundle.add("since_id", since_id + "");
        if (max_id != null)
            bundle.add("max_id", max_id + "");
        if (count != -1)
            bundle.add("count", count + "");
        if (page != -1)
            bundle.add("page", page + "");

        String url = Weibo.SERVER + "statuses/repost_timeline.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
      * statuses/repost_by_me
      *    n
      * @param id   id  
     * @param since_id null IDsince_idsince_id
     * @param max_id IDmax_id  null
     * @param count 20 200  -1
     * @param page     1  
     */
    public List<Status> getRepostByMe(Long id, Long since_id, Long max_id, int count, int page)
            throws WeiboException {
        String content = repost_By_Me(this, id, since_id, max_id, count, page);
        return getStatusList(content);
    }

    private String repost_By_Me(Weibo weibo, Long id, Long since_id, Long max_id, int count, int page)
            throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        bundle.add("id", id + "");
        if (since_id != null)
            bundle.add("since_id", since_id + "");
        if (max_id != null)
            bundle.add("max_id", max_id + "");
        if (count != -1)
            bundle.add("count", count + "");
        if (page != -1)
            bundle.add("page", page + "");

        String url = Weibo.SERVER + "statuses/repost_by_me.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     * ID
     * :idID400"40031:Error: target weibo does not exist!"
     * @param id Rest     
     */
    public Status getShowStatus(Long id) throws WeiboException {
        String content = showStatus(this, APP_KEY, id);
        return getStatus(content);
    }

    private String showStatus(Weibo weibo, String source, Long id) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", Weibo.APP_KEY);

        String url = Weibo.SERVER;
        if (id != null)
            url = url + "statuses/show/" + id + ".json";
        else
            url = url + "statuses/show.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    private List<Status> getMentions(String content) throws WeiboException {
        List<Status> mentionsList = new ArrayList<Status>();
        try {

            JSONArray jarray = new JSONArray(content);
            for (int i = 0; i < jarray.length(); i++) { //
                Status mention = new Status();
                JSONObject json = jarray.getJSONObject(i);
                mention.setCreated_at((new Date(json.getString("created_at"))));
                mention.setFavorited(json.getBoolean("favorited"));
                mention.setId(json.getLong("id"));
                mention.setIn_reply_to_screen_name(json.getString("in_reply_to_screen_name"));
                if (!json.isNull("in_reply_to_status_id"))
                    mention.setIn_reply_to_status_id(json.getString("in_reply_to_status_id"));
                else
                    mention.setIn_reply_to_status_id(null);
                if (!json.isNull("in_reply_to_user_id"))
                    mention.setIn_reply_to_user_id(json.getString("in_reply_to_user_id"));
                else
                    mention.setIn_reply_to_user_id(null);
                mention.setSource(json.getString("source"));
                //          mention.setRetweetedStatus((Status) json.get("retweeted_status"));

                if (!json.isNull("retweeted_status")) {
                    String retweeted_rlt = json.getString("retweeted_status");
                    Status retweeted_status = getStatus(retweeted_rlt);
                    mention.setRetweetedStatus(retweeted_status);
                }
                mention.setText(json.getString("text"));
                mention.setTruncated(json.getBoolean("truncated"));
                //          mention.setUser((User) json.get("user")); 

                if (!json.isNull("user")) {
                    String user_rlt = json.getString("user");
                    User user = getUser(user_rlt);
                    mention.setUser(user);
                }
                mentionsList.add(mention); //Add in List<>

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return mentionsList;
    }

    /**
     * n@username 
     * @param since_id IDsince_id
     * since_id
     * @param max_id  IDmax_id   
     */
    public List<Status> getMentions(Long since_id, Long max_id, int count, int page) throws WeiboException {
        String content = mentions(this, Weibo.APP_KEY, since_id, max_id, count, page);
        return getMentions(content);
    }

    private String mentions(Weibo weibo, String source, Long since_id, Long max_id, int count, int page)
            throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", Weibo.APP_KEY);
        if (since_id != null)
            bundle.add("since_id", since_id + "");
        if (max_id != null)
            bundle.add("max_id", max_id + "");
        if (count != -1)
            bundle.add("count", count + "");
        if (page != -1)
            bundle.add("page", page + "");

        String url = Weibo.SERVER + "statuses/mentions.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    //==========User===============================
    private List<User> getUserList(String content) throws WeiboException {
        List<User> users = new ArrayList<User>();
        try {
            JSONArray jarry = new JSONArray(content);
            for (int index = 0; index < jarry.length(); index++) {
                JSONObject json = jarry.getJSONObject(index);
                User user = new User();
                user.setCity(json.getLong("city"));
                user.setCreated_at(new Date(json.getString("created_at")));
                user.setDescription(json.getString("description"));
                user.setDomain(json.getString("domain"));
                user.setFavourites_count(json.getInt("favourites_count"));
                user.setFollowers_count(json.getInt("followers_count"));
                user.setFollowing(json.getBoolean("following"));
                user.setFriends_count(json.getInt("friends_count"));
                user.setGender(json.getString("gender"));
                user.setId(json.getLong("id"));
                user.setLocation(json.getString("location"));
                user.setName(json.getString("name"));
                user.setProfile_image_url(json.getString("profile_image_url"));
                user.setProvince(json.getLong("province"));
                user.setScreen_name(json.getString("screen_name"));
                user.setStatuses_count(json.getInt("statuses_count"));
                user.setUrl(json.getString("url"));
                user.setVerified(json.getBoolean("verified"));

                if (!json.isNull("retweeted_status")) {
                    String retweeted_rlt = json.getString("retweeted_status");
                    Status retweeted_status = getStatus(retweeted_rlt);
                    user.setStatus(retweeted_status);
                }
                users.add(user);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return users;
    }

    private User getUser(String content) throws WeiboException {
        User user = new User();
        try {
            JSONObject json = new JSONObject(content);
            user.setCity(json.getLong("city"));
            user.setCreated_at(parseDate(json.getString("created_at"), "EEE MMM dd HH:mm:ss z yyyy"));
            user.setId(json.getLong("id"));
            user.setDescription(json.getString("description"));
            user.setDomain(json.getString("domain"));
            user.setFavourites_count(json.getInt("favourites_count"));
            user.setFollowers_count(json.getInt("followers_count"));
            user.setFollowing(json.getBoolean("following"));
            user.setFriends_count(json.getInt("friends_count"));
            user.setGender(json.getString("gender"));
            user.setLocation(json.getString("location"));
            user.setName(json.getString("name"));
            user.setProfile_image_url(json.getString("profile_image_url"));
            user.setProvince(json.getLong("province"));
            user.setScreen_name(json.getString("screen_name"));
            user.setStatuses_count(json.getInt("statuses_count"));
            user.setUrl(json.getString("url"));
            user.setVerified(json.getBoolean("verified"));

            if (!json.isNull("retweeted_status")) {
                String retweeted_rlt = json.getString("retweeted_status");
                Status retweeted_status = getStatus(retweeted_rlt);
                user.setStatus(retweeted_status);
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return user;
    }

    /**
     * users/suggestions  GET  
     * @param    with_reason  1/0
     * 1   
     *  with_reason 
     */
    public List<User> getSuggestions(int with_reason) throws WeiboException {
        String content = suggestions(this, APP_KEY, with_reason);
        return getUserList(content);
    }

    private String suggestions(Weibo weibo, String source, int with_reason) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", Weibo.APP_KEY);
        if (with_reason != -1)
            bundle.add("since_id", with_reason + "");

        String url = Weibo.SERVER + "users/suggestions.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     *    users/hot     
     * category default<br>
     * default<br>
     * ent<br>
     * hk_famous<br>
     * model<br>
     * cooking&<br>
     * sport<br>
     * finance<br>
     * techIT<br>
     * singer<br>
     * writer<br>
     * moderator<br>
     * medium<br>
     * stockplayer<br>
     * @throws WeiboException 
     */
    public List<User> getHot(String source, String category) throws WeiboException {
        String content = hot(this, APP_KEY, category);
        return getUserList(content);
    }

    private String hot(Weibo weibo, String source, String category) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", Weibo.APP_KEY);
        if (category != null)
            bundle.add("category", category);

        String url = Weibo.SERVER + "statuses/repost_timeline.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     * 
     *   
     * @param screen_name 
     * @param cursor 
     * 1cursor-1next_cursor
     * cursornext_cursor0
     * 
     * @param id id 
     * @param count  20200 -1 
     * @throws WeiboException 
     */
    public List<User> getFollowers(String id, Long user_id, String screen_name, int cursor, int count)
            throws WeiboException {
        String content = followers(this, id, user_id, screen_name, cursor, count);
        return getUserList(content);
    }

    private String followers(Weibo weibo, String id, Long user_id, String screen_name, int cursor, int count)
            throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        if (user_id != null)
            bundle.add("since_id", user_id + "");
        if (screen_name != null)
            bundle.add("screen_name", screen_name + "");
        if (count != -1)
            bundle.add("count", count + "");
        if (cursor != -1)
            bundle.add("page", cursor + "");

        String url = Weibo.SERVER;
        if (id != null)
            url = url + "statuses/followers/" + id + ".json";
        else
            url = url + "statuses/followers.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     *   
     * @param screen_name
     * @param cursor
     * 1cursor-1next_
     * cursorcursornext_cursor0
     * 
     * @param id id 
     * @param count  20200 -1 
     * @throws WeiboException 
     */
    public List<User> getFiends(String id, Long user_id, String screen_name, int cursor, int count)
            throws WeiboException {
        String content = friends(this, id, user_id, screen_name, cursor, count);
        return getUserList(content);
    }

    private String friends(Weibo weibo, String id, Long user_id, String screen_name, int cursor, int count)
            throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        if (user_id != null)
            bundle.add("since_id", user_id + "");
        if (screen_name != null)
            bundle.add("screen_name", screen_name + "");
        if (count != -1)
            bundle.add("count", count + "");
        if (cursor != -1)
            bundle.add("page", cursor + "");

        String url = Weibo.SERVER;
        if (id != null)
            url = url + "statuses/friends/" + id + ".json";
        else
            url = url + "statuses/friends.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**users/show  
     *  user_id screen name  User
     * @param id   REST user_id screen_name <br>   
     * <br>id user_id screen_name 
     */
    public User getUser(String id, Long user_id, String screen_name) throws WeiboException {
        String content = user(this, id, user_id, screen_name);
        return getUser(content);
    }

    private String user(Weibo weibo, String id, Long user_id, String screen_name) throws WeiboException {
        // TODO Auto-generated method stub
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        if (user_id != null)
            bundle.add("user_id", user_id + "");
        if (screen_name != null)
            bundle.add("screen_name", screen_name);
        String url = Weibo.SERVER;
        if (id != null)
            url = url + "users/show/" + id + ".json";
        else
            url = url + "users/show.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_POST, getAccessToken());
        return rlt;
    }

    //=WeiboRequest.java======================================================
    /**
        * 
        * @param context The Activity context
        * @param weibo   An instance of weibo
        * @param source   AppKey of this applicationOAuth
        * @param file    A path of image (What consumers want to upload)
        * @param status   
        * @param lon 
        * @param lat 
        * @return
        * @throws WeiboException
        */
    public String upload(Weibo weibo, String file, String status, String lon, String lat) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        bundle.add("pic", file);
        bundle.add("status", status);
        if (!TextUtils.isEmpty(lon) && (!TextUtils.isEmpty(lat))) {
            bundle.add("lon", lon);
            bundle.add("lat", lat);
        }
        String rlt = "";
        String url = Weibo.SERVER + "statuses/upload.json";
        rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_POST, OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     * POST
     * @param cid  int64   ID
     * @param comment URLEncode,140
     * @param id ID
     * @param without_mention @<br>
     * 0@.0.
     * 
     */
    public Comment postReply(Weibo weibo, Long cid, String comment, Long id, int without_mention) {
        Comment comments = new Comment();
        try {
            JSONObject json = new JSONObject(reply(weibo, cid, comment, id, without_mention));
            comments.setCreated_at(new Date(json.getString("created_at")));
            //            comments.setFavorited(json.getBoolean("favorited"));
            comments.setId(json.getLong("id"));
            //             comments.setSource(json.getString("source"));    
            //             comments.setStatus((Status) json.get("retweeted_status"));
            if (!json.isNull("retweeted_status")) {
                String retweeted_rlt = json.getString("retweeted_status");
                Status retweeted_status = getStatus(retweeted_rlt);
                comments.setStatus(retweeted_status);
            }
            comments.setText(json.getString("text"));
            //             comments.setTruncated(json.getBoolean("truncated"));
            //             comments.setUser((User) json.get("user"));

            if (!json.isNull("user")) {
                String user_rlt = json.getString("user");
                User user = getUser(user_rlt);
                comments.setUser(user);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (WeiboException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return comments;
    }

    private String reply(Weibo weibo, Long cid, String comment, Long id, int without_mention)
            throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        bundle.add("cid", cid + "");
        bundle.add("comment", comment);
        bundle.add("id", id + "");
        if (without_mention != -1)
            bundle.add("without_mention", without_mention + "");
        String url = Weibo.SERVER + "statuses/reply.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_POST, getAccessToken());
        return rlt;
    }

    /**
     * POST 
     * <br>annotation  
     * @param status       
     * @param in_reply_to_status_id
     * @param lon
     * @param lat
     * @return
     * @throws WeiboException
     * @throws JSONException
     */
    public Status update(String status, Long in_reply_to_status_id, String lon, String lat)
            throws WeiboException, JSONException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        bundle.add("status", status);
        if (in_reply_to_status_id != null)
            bundle.add("in_reply_to_status_id", in_reply_to_status_id + "");
        if (!TextUtils.isEmpty(lon) && (!TextUtils.isEmpty(lat))) {
            bundle.add("lon", lon);
            bundle.add("lat", lat);
        }
        String rlt = "";
        String url = Weibo.SERVER + "statuses/update.json";
        rlt = this.request(url, bundle, Utility.HTTPMETHOD_POST, getAccessToken());

        Status rtn = getStatus(rlt);
        return rtn;
    }

    //    statuses/repost
    /** POST
     *    01
     *    23120
     */
    public Status repost(Long id, String status, int is_comment) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        bundle.add("id", id + "");
        if (status != null)
            bundle.add("status", status);
        if (is_comment != -1)
            bundle.add("is_comment", is_comment + "");
        String url = Weibo.SERVER + "statuses/repost.json";
        String rnt = this.request(url, bundle, Utility.HTTPMETHOD_POST, getAccessToken());
        Status stus = getStatus(rnt);
        return stus;

    }

    /**
     * friendships/exists 
     * ABABtruefalse 
     * @param user_a
     * @param user_b 
     */
    public Boolean getFriendshipsExists(Long user_a, Long user_b) throws WeiboException, JSONException {
        // TODO Auto-generated method stub
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        bundle.add("user_a", user_a + "");
        bundle.add("user_b", user_b + "");
        String url = Weibo.SERVER + "friendships/exists.json";
        String rtn = this.request(url, bundle, Utility.HTTPMETHOD_GET, getAccessToken());
        JSONObject json = new JSONObject(rtn);
        return json.getBoolean("friends");
    }

    //   friendships/show
    //   
    //   target_id   false   int64   ID
    //   target_screen_name   false   string   

    /**
     * following 0   1 
     * following  followingtrue3  2
     */
    public int getFriendShips_Show(Long target_id, String target_screen_name) throws WeiboException, JSONException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        if (target_id != null)
            bundle.add("target_id", target_id + "");
        if (target_screen_name != null)
            bundle.add("target_screen_name", target_screen_name);
        String url = Weibo.SERVER + "friendships/show.json";
        String rtn = this.request(url, bundle, Utility.HTTPMETHOD_GET, getAccessToken());
        JSONObject json = new JSONObject(rtn);
        JSONObject target_json = json.getJSONObject("target");
        Boolean following = target_json.getBoolean("following");
        Boolean followed_by = target_json.getBoolean("followed_by");
        int a, b;
        a = b = 0;
        if (following)
            a = 1;
        if (followed_by)
            b = 1;
        if (a == b)
            return a & b; // 0   1
        else
            return 2 + a; //ab  a13  2
    }

    /**
     * n
     * 20  
     * @param ids  ID 
     */
    private String counts(Long[] ids) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();

        String idsa = "";

        for (int i = 0; i < ids.length; i++) {
            //      
            if (i == ids.length - 1) {
                idsa = idsa + ids[i] + "";
            } else {
                idsa = idsa + ids[i] + ",";
            }
        }
        Log.e("IDS", idsa);

        idsa = URLEncoder.encode(idsa);
        bundle.add("ids", idsa);
        bundle.add("source", APP_KEY);
        String url = Weibo.SERVER + "statuses/counts.json";
        String rlt = this.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    /**
     * n
     * 20  
     * @param ids  ID 
     */
    public List<Count> getCount(Long[] ids) throws JSONException {
        String content;
        List<Count> result = new ArrayList<Count>();

        try {

            content = counts(ids);
            Log.e("content", content);

            JSONArray jarray = new JSONArray(content);

            for (int i = 0; i < jarray.length(); i++) {
                JSONObject json = jarray.getJSONObject(i);
                Count count = new Count();
                count.setComments(json.getInt("comments"));
                count.setRt(json.getInt("rt"));
                count.setId(json.getLong("id"));

                result.add(count);
            }
        } catch (WeiboException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    protected static Date parseDate(String str, String format) throws WeiboException {
        if (str == null || "".equals(str)) {
            return null;
        }
        SimpleDateFormat sdf = formatMap.get(format);
        if (null == sdf) {
            sdf = new SimpleDateFormat(format, Locale.ENGLISH);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
            formatMap.put(format, sdf);
        }
        try {
            synchronized (sdf) {
                // SimpleDateFormat is not thread safe
                return sdf.parse(str);
            }
        } catch (ParseException pe) {
            throw new WeiboException("Unexpected format(" + str + ") returned from sina.com.cn");
        }
    }

    //   account/verify_credentials
    //   
    //    http 200403
    //   source
    private String verify_credentials(Weibo weibo) throws WeiboException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        String url = Weibo.SERVER + "account/verify_credentials.json";
        String rlt = weibo.request(url, bundle, Utility.HTTPMETHOD_POST,
                OAuthConstant.getInstance().getAccessToken());
        return rlt;
    }

    public User verify_credentials() throws WeiboException {
        String content = verify_credentials(this);
        User user = getUser(content);
        return user;
    }

    /**
     *  service
     * @param with_new_status 0  
     * @param since_id   with_new_status
     */
    public StatusCounts unread(int with_new_status, Long since_id) throws WeiboException, JSONException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        if (with_new_status == 1)
            bundle.add("with_new_status", 1 + "");
        if (since_id != null)
            bundle.add("since_id", since_id + "");
        String url = Weibo.SERVER + "statuses/unread.json";
        String rlt = this.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());

        Log.e("unreadJson", rlt);

        JSONObject json = new JSONObject(rlt);
        StatusCounts counts = new StatusCounts();
        counts.setComments(json.getInt("comments"));
        counts.setDm(json.getInt("dm"));
        counts.setFollowers(json.getInt("followers"));
        counts.setMentions(json.getInt("mentions"));
        //      counts.setNew_status(json.getInt("new_status"));  
        return counts;
    }

    /**
     *  
     * @param type 1~4  1 2@me 3
     * 4
     * @return
     * @throws WeiboException 
     * @throws JSONException 
     */
    public Boolean resetCount(int type) throws WeiboException, JSONException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        bundle.add("type", type + "");
        String url = Weibo.SERVER + "statuses/reset_count.json";
        String rlt = this.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        JSONObject json = new JSONObject(rlt);
        return json.getBoolean("result");
    }

    /**
     *    
     */
    public Boolean helpTest() throws WeiboException, JSONException {
        WeiboParameters bundle = new WeiboParameters();
        bundle.add("source", APP_KEY);
        String url = Weibo.SERVER + "help/test.json";
        String rlt = this.request(url, bundle, Utility.HTTPMETHOD_GET,
                OAuthConstant.getInstance().getAccessToken());
        JSONObject json = new JSONObject(rlt);
        return json.getBoolean("ok");
    }

    private void setNetWorkIsError(Boolean r) {
        netWorkIsError = r;
    }

    public static Boolean getNetWorkIsError() {
        return netWorkIsError;
    }
}