Sina Micro-Blog API Simple call

Source: Internet
Author: User
Tags oauth string to json stringbuffer
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 Night Crab * Microblogging share * * * @SuppressWarnings ("serial") @Scope ("prototype") @Controller ("Weiboaction") public class We Iboaction extends Baseaction {private static String code;//Login Return code/** Webcode to the session * * private static final String Web_accesstoken = "Web_accesstoken";
	private string Total_number= "";//Weibo total number of users public string token = ""; public string content = "";//Publish The content information of the microblogging string url= "";/need long link to short link URL private int count=30;//per page display number default * bit friend/** * Page Turn C Ursor/Private String cursor;//page forward to-1 page back to 1 private int next_cursor=0;//Next next to the subscript private int previous_cursor=0;//prev

	
	The subscript private String weibo_url= "";
			/** * Obtain user authorization 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 to "success"; /** * Get Friends Mutual powder Information */public String getfriendsbilateral () {Accesstoken at = getsessionvalue (web_accesstoken) = = nul L?
		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; }/* Get friends Mutual Powder Information SDK spelling 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")) {//page forward next_cursor=next_cursor-count*2;
					}else{//backward page 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);
		The catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
		} renderjson (Message) (Utiltools.encodeobject2json);
	return null; * * */** * Get the user's fan list */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; }/** * Resolution URL RETURNS the JSON string * @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);
		  String to JSON object if (Returnstr!=null&&!returnstr.equals ("")) {map = Jsonstrtomap (RETURNSTR);
			The catch (Exception e) {System.out.println ("error>>>>");
		E.printstacktrace ();
	} return Utiltools.encodeobject2json (map); /* * Get user's fan List SDK notation public String Getfollowersbyid () {map<string,object> map=new Hashmap<string,object&gt
		;();
		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")) {//page forward next_cursor=next_cursor-count*2;
					}else{//backward page 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);
		The catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
		} Renderjson (Utiltools.encodeobject2json (map));
		
	return null; }*//** * Get the user's attention list * Solution URL catch content/public String Getfriendsbyid () {Accesstoken at = getsessionvalue (web_access TOKEN) = = 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+" &
		Amp;cursor= "+next_cursor+" &access_token= "+at.getaccesstoken" ();
		} Renderjson (Returnstr (Weibo_url));
	return null; /* Get the user's attention List SDK notation 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")) {//page forward next_cursor=next_cursor-count*2; }else{//back Page 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);
		The catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
		} renderjson (Message) (Utiltools.encodeobject2json);
	return null;
		* * */** * Publish micro bo/public string Sendweibo () {String message = ""; try {if (content!= null &&!content.equals ("")) {Accesstoken at = getsessionvalue (web_accesstoken) = = Nu ll?
				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);
					Publish success 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; /** * variable file is byte * @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 the bytes have been read in if (offset < bytes.length) {throw new IOException (' could not co
			mpletely Read File "+ file.getname ());
		}//close the input stream and return bytes is.close ();
		catch (Exception e) {throw new RuntimeException (e);
	return bytes;
		/** * Parse Get short link * @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);
			String to json object Short_url = Geturlfromjson (RETURNSTR); The catch (Exception e) {System.out.println ("Error>>>> ");
			E.printstacktrace ();
		}} rendertext (Short_url);
  
    return null; Dynamic resolution URL in/** * action returns JSON * only support GET request/private string Getbackjson (string url) {StringBuffer htmlbuf
		fer = 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> ();
	        Outermost parse Jsonobject JSON = Jsonobject.fromobject (JSONSTR); For (Object K:json.keyset (){Object v = json.get (k); If the inner layer is still an array, continue parsing if (v instanceof jsonarray) {list<map<string, object>> List = n
	                EW 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; /** * Get the returned JSON data fetch short link * @param jsonstring * @return/public static String Geturlfromjson (Str
		   ing 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;
	The 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;
	The public void setprevious_cursor (int previouscursor) {previous_cursor = Previouscursor; }



	
	
}

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.