`
tanglong8848
  • 浏览: 66863 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

新浪微博API简单调用

 
阅读更多
package com
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import weibo4j.Oauth;
import weibo4j.Timeline;
import weibo4j.Weibo;
import weibo4j.examples.timeline.Upload;
import weibo4j.http.AccessToken;
import weibo4j.http.ImageItem;
import weibo4j.model.Status;
import weibo4j.util.WeiboConfig;

import com.xxx.common.UtilTools;
import com.xxx.frame.util.ApplicationResources;
/**
 * @author 暗夜螃蟹
 * 微博分享
 */
@SuppressWarnings("serial")
@Scope("prototype")
@Controller("WeiboAction")
public class WeiboAction extends BaseAction {

	private static String code; // 登录返回的code
	/** 存入session的webcode */
	private static final String WEB_ACCESSTOKEN = "WEB_ACCESSTOKEN";
    private String total_number="";//微博总用户数
	public String token = "";
	public String content = "";//发布微博的内容信息
	String url="";//需要长链接变短链接的URL
	private int count=30;//每页显示数量 默认* 位好友
	/**
	 * 翻页的cursor
	 */
	private String cursor;//向前翻页为-1向后翻页为1
	private int next_cursor=0;//下一页的下标
	private int previous_cursor=0;//上一页的下标
	private String weibo_url="";

	
	/**
	 * 获得用户授权token
	 */
	public String getWeiboToken() {
		try {
			Oauth oauth = new Oauth();
			AccessToken at = oauth.getAccessTokenByCode(code);
			token = at.getAccessToken();
			setSessionValue(WEB_ACCESSTOKEN, at);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return "success";
	}

	/**
	 * 得到朋友互粉信息
	 */
	public String getFriendsBilateral(){
		AccessToken at = getSessionValue(WEB_ACCESSTOKEN) == null ? null: (AccessToken) getSessionValue(WEB_ACCESSTOKEN);
		if (at != null) {
			weibo_url=WeiboConfig.getValue("baseURL")+"friendships/bilateral.json?uid="+at.getUid()+"&access_token="+at.getAccessToken();
		}
		renderJson(returnStr(weibo_url));
		return null;
		
	}
	/* 得到朋友互粉信息 SDK写法
	public String getFriendsBilateral(){
		Map<String,Object> map=new HashMap<String,Object>();
		List<User> message=new ArrayList<User>();
		AccessToken at = getSessionValue(WEB_ACCESSTOKEN) == null ? null: (AccessToken) getSessionValue(WEB_ACCESSTOKEN);
		try {
			if (at != null) {
				Weibo weibo = new Weibo();
				weibo.setToken(at.getAccessToken());
				Users user=new Users();
				user.showUserById(at.getUid());
				Friendships friends = new Friendships();
				if(cursor!=null&&!cursor.equals("")){
					if(cursor.equals("-1")){//向前翻页
						next_cursor=next_cursor-count*2;
					}else{//向后翻页
						next_cursor=next_cursor+count;
					}
				}
				String total=String.valueOf(count);
				String page_cursor=String.valueOf(next_cursor);
				message=friends.getFriendsBilateral(at.getUid(),page_cursor,total).getUsers();
				if(page_cursor!=null&&page_cursor.equals("0")){
					page_cursor=String.valueOf(message.size());
				}
				map.put("User", message);
				map.put("next_cursor",page_cursor);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		renderJson(UtilTools.encodeObject2Json(message));
		return null;
	}
	*/
	
	/**
	 * 获取用户的粉丝列表
	 */
	
	public String getFollowersById(){
		AccessToken at = getSessionValue(WEB_ACCESSTOKEN) == null ? null: (AccessToken) getSessionValue(WEB_ACCESSTOKEN);
		if (at != null) {
			if(cursor!=null&&cursor.equals("-1")){
				next_cursor=next_cursor-count;
				if(next_cursor<0){
					next_cursor=0;
				}
			}
			weibo_url=WeiboConfig.getValue("baseURL")+"friendships/followers.json?uid="+at.getUid()+"&count="+count+"&cursor="+next_cursor+"&previous_cursor="+previous_cursor+"&access_token="+at.getAccessToken();
		}
		renderJson(returnStr(weibo_url));
		return null;
	}
	
	/**
	 * 解析URL后返回Json字符串
	 * @param url
	 * @return
	 */
	public String returnStr(String post_url){
		Map<String,Object> map=new HashMap<String,Object>();
		if(post_url!=null&&!post_url.equals("")){
		try {
		String	returnStr=getBackJson(post_url);
			// 字符串转JSON对象
		  if(returnStr!=null&&!returnStr.equals("")){
			map = jsonStrToMap(returnStr);
		  }
		} catch (Exception e) {
			System.out.println("error>>>>");
			e.printStackTrace();
		}
		}
	    return UtilTools.encodeObject2Json(map);
	}
	
	
	/*获取用户的粉丝列表 SDK写法
	public String getFollowersById(){
		Map<String,Object> map=new HashMap<String,Object>();
		List<User> message=new ArrayList<User>();
		AccessToken at = getSessionValue(WEB_ACCESSTOKEN) == null ? null: (AccessToken) getSessionValue(WEB_ACCESSTOKEN);
		try {
			if (at != null) {
				Weibo weibo = new Weibo();
				weibo.setToken(at.getAccessToken());
				Users user=new Users();
				user.showUserById(at.getUid());
				Friendships friends = new Friendships();
				if(cursor!=null&&!cursor.equals("")){
					if(cursor.equals("-1")){//向前翻页
						next_cursor=next_cursor-count*2;
					}else{//向后翻页
						next_cursor=next_cursor+count;
					}
				}
				String total=String.valueOf(count);
				String page_cursor=String.valueOf(next_cursor);

				message=friends.getFollowersById(at.getUid(),page_cursor,total).getUsers();
				if(page_cursor!=null&&page_cursor.equals("0")){
					page_cursor=String.valueOf(message.size());
				}
				map.put("User", message);
				map.put("next_cursor",page_cursor);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		renderJson(UtilTools.encodeObject2Json(map));
		return null;
		
	}*/
	
	
	/**
	 * 获取用户的关注列表
	 * 解URL抓内容
	 */
	public String getFriendsByID(){
		AccessToken at = getSessionValue(WEB_ACCESSTOKEN) == null ? null: (AccessToken) getSessionValue(WEB_ACCESSTOKEN);
		if (at != null) {
			if(cursor!=null&&cursor.equals("-1")){
				next_cursor=next_cursor-count;
				if(next_cursor<0){
					next_cursor=0;
				}
			}
			weibo_url=WeiboConfig.getValue("baseURL")+"friendships/friends.json?uid="+at.getUid()+"&count="+count+"&cursor="+next_cursor+"&access_token="+at.getAccessToken();
		}
		renderJson(returnStr(weibo_url));
		return null;
	}
	
	
	/*获取用户的关注列表 SDK写法
	public String getFriendsByID(){
		Map<String,Object> map=new HashMap<String,Object>();
		List<User>  message=new ArrayList<User>();
		AccessToken at = getSessionValue(WEB_ACCESSTOKEN) == null ? null: (AccessToken) getSessionValue(WEB_ACCESSTOKEN);
		try {
			if (at != null) {
				Weibo weibo = new Weibo();
				weibo.setToken(at.getAccessToken());
				Users user=new Users();
				user.showUserById(at.getUid());
				
				Friendships friends = new Friendships();
				if(cursor!=null&&!cursor.equals("")){
					if(cursor.equals("-1")){//向前翻页
						next_cursor=next_cursor-count*2;
					}else{//向后翻页
						next_cursor=next_cursor+count;
					}
				}
				String total=String.valueOf(count);
				String page_cursor=String.valueOf(next_cursor);
				message=friends.getFriendsByID(at.getUid(),page_cursor,total).getUsers();
				if(page_cursor!=null&&page_cursor.equals("0")){
					page_cursor=String.valueOf(message.size());
				}
				map.put("User", message);
				map.put("next_cursor",page_cursor);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		renderJson(UtilTools.encodeObject2Json(message));
		return null;
	}
	*/
	


	/**
	 * 发布微博 
	 */
	public String sendWeibo() {
		String message = "";
		try {
			if (content != null && !content.equals("")) {
				AccessToken at = getSessionValue(WEB_ACCESSTOKEN) == null ? null: (AccessToken) getSessionValue(WEB_ACCESSTOKEN);
				if (at != null) {
					Weibo weibo = new Weibo();
					weibo.setToken(at.getAccessToken());
					byte[] img = Upload.readFileImage(ServletActionContext.getServletContext().getRealPath("/")+ApplicationResources.getText("weibo.sharePic"));
					ImageItem pic = new ImageItem("pic", img);
					String text = java.net.URLEncoder.encode(content, "utf-8");
					Timeline tl = new Timeline();
					Status status =tl.UploadStatus(text, pic);
					// 发布成功
					if (null != status) {
						message = "{\"success\":\"true\"}";
					} else {
						message = "{\"success\":\"false\"}";
					}
				} else {
					message = "{\"success\":\"false\"}";
				}
			} else {
				message = "{\"success\":\"false\"}";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderJson(message);
		return null;
	}
 
	/**
	 * 变文件为字节
	 * @param file
	 * @return
	 */
	public static byte[] getBytesFromFile(File file) {

		long length = file.length();
		byte[] bytes = new byte[(int) length];

		try {
			InputStream is = new FileInputStream(file);

			// Read in the bytes
			int offset = 0;
			int numRead = 0;
			while (offset < bytes.length
					&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
				offset += numRead;
			}

			// Ensure all the bytes have been read in
			if (offset < bytes.length) {
				throw new IOException("Could not completely read file "+ file.getName());
			}

			// Close the input stream and return bytes
			is.close();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return bytes;
	}
	
	/**
	 * 解析获取短链接
	 * @param url
	 * @return
	 */
	public String getSortURL() {  
		String returnStr="";
		String short_url = "";
AccessToken at = getSessionValue(WEB_ACCESSTOKEN) == null ? null: (AccessToken) getSessionValue(WEB_ACCESSTOKEN);
      if (at != null) {
		if (url != null && !url.equals("")) {
			String urlSource = "https://api.weibo.com/2/short_url/shorten.json?url_long="+ url + "&access_token="+at.getAccessToken();

			try {
				returnStr=getBackJson(urlSource);
				// 字符串转JSON对象
				short_url = getURLFromJson(returnStr);
			} catch (Exception e) {
				System.out.println("error>>>>");
				e.printStackTrace();
			}
			
		}
          }
		renderText(short_url);
		return null;
  
    }  
	
	
	
	/**
	 * Action中动态解析URL返回Json
	 * 只支持GET请求
	 */
	 private String getBackJson(String url){
		StringBuffer htmlBuffer = new StringBuffer();
		String returnStr = null;
		try {
			InputStream inputSource = new URL(url).openStream();
			int ch;
			while ((ch = inputSource.read()) > -1) {
				htmlBuffer.append((char) ch);
			}
			inputSource.close();
			returnStr = new String(htmlBuffer);
			returnStr = new String(returnStr.getBytes("ISO8859_1"),"UTF-8");
		} catch (Exception e) {
			System.out.println("error>>>>");
			e.printStackTrace();
		}
		return returnStr;
	}
	
	
	 /**
	  * JsonString to map
	  */
	 public static Map<String, Object> jsonStrToMap(String jsonStr){
	        Map<String, Object> map = new HashMap<String, Object>();
	        //最外层解析
	        JSONObject json = JSONObject.fromObject(jsonStr);
	        for(Object k : json.keySet()){
	            Object v = json.get(k); 
	            //如果内层还是数组的话,继续解析
	            if(v instanceof JSONArray){
	                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
	                Iterator<JSONObject> it = ((JSONArray)v).iterator();
	                while(it.hasNext()){
	                    JSONObject json2 = it.next();
	                    list.add(jsonStrToMap(json2.toString()));
	                }
	                map.put(k.toString(), list);
	            } else {
	                map.put(k.toString(), v);
	            }
	        }
	        return map;
	    }
    /**
     * 获得返回的JSON数据取短链接
     * @param jsonString
     * @return
     */
	 public static String getURLFromJson(String jsonString) {
		 String str="";
		   JSONObject jsonObject = JSONObject.fromObject(jsonString); 
	        if(jsonObject.getJSONArray("urls")!=null){
	        	JSONArray arr=jsonObject.getJSONArray("urls");
	        	for(int i=0;i<arr.size();i++){
	        		JSONObject c=arr.getJSONObject(i);
	        		str=String.valueOf(c.get("url_short")); 
	        	}
	        }
		  return str;
	}
	
	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public static String getWebAccesstoken() {
		return WEB_ACCESSTOKEN;
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getCursor() {
		return cursor;
	}

	public void setCursor(String cursor) {
		this.cursor = cursor;
	}

	public int getNext_cursor() {
		return next_cursor;
	}

	public void setNext_cursor(int nextCursor) {
		next_cursor = nextCursor;
	}

	public String getTotal_number() {
		return total_number;
	}

	public void setTotal_number(String totalNumber) {
		total_number = totalNumber;
	}

	public int getPrevious_cursor() {
		return previous_cursor;
	}

	public void setPrevious_cursor(int previousCursor) {
		previous_cursor = previousCursor;
	}



	
	
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics