校内应用API开发源码

目前在51,校内,facebook开发小应用越来越热,这里我仅以xiaonei.com提供的APP Java API为例,探讨他的实现方法,简单来说就是分为2步:

  1. 申请个应用,得到应用的API Key和Secret两个数值
  2. 利用这两个数值,我们就可以使用xiaonei的Java API,以下代码用来实现获取你的个人信息和你的好友信息代码(由于邀请API已过期,所以不能使用):
Java代码 复制代码
  1. package com.cxlh.servlet;   
  2.   
  3. import java.io.IOException;   
  4. import java.util.ArrayList;   
  5. import java.util.EnumSet;   
  6. import java.util.List;   
  7.   
  8. import javax.servlet.ServletException;   
  9. import javax.servlet.http.HttpServlet;   
  10. import javax.servlet.http.HttpServletRequest;   
  11. import javax.servlet.http.HttpServletResponse;   
  12.   
  13. import org.w3c.dom.Document;   
  14.   
  15. import com.common.utils.StrCharUtil;   
  16. import com.xiaonei.api.ProfileField;   
  17. import com.xiaonei.api.XiaoneiException;   
  18. import com.xiaonei.api.XiaoneiRestClient;   
  19. import com.xiaonei.api.schema.Friend;   
  20. import com.xiaonei.api.schema.FriendsGetFriendsResponse;   
  21. import com.xiaonei.api.schema.RequestsSendRequestResponse;   
  22. import com.xiaonei.api.schema.UsersGetInfoResponse;   
  23.   
  24. import net.sf.json.JSONArray;   
  25. import net.sf.json.JSONObject;   
  26.   
  27.   
  28. /**  
  29.  * Servlet implementation class XN  
  30.  */  
  31. public class XN extends HttpServlet {   
  32.     private static final long serialVersionUID = 1L;   
  33.        
  34.     public static String PARAM_XN_SIG_IN_IFRAME = "xn_sig_in_iframe";   
  35.   
  36.     public static String PARAM_XN_SIG_TIME = "xn_sig_time";   
  37.   
  38.     public static String PARAM_XN_SIG_ADDED = "xn_sig_added";   
  39.   
  40.     public static String PARAM_XN_SIG_USER = "xn_sig_user";   
  41.   
  42.     public static String PARAM_XN_SIG_SESSION_KEY = "xn_sig_session_key";   
  43.   
  44.     public static String PARAM_XN_SIG_API_KEY = "xn_sig_api_key";      
  45.           
  46.     /**  
  47.      * @see HttpServlet#HttpServlet()  
  48.      */  
  49.     public XN() {   
  50.         super();   
  51.         // TODO Auto-generated constructor stub   
  52.     }   
  53.   
  54.     private List<Friend> getFriend(XiaoneiRestClient client) throws Exception{   
  55.         client.friends_getFriends();   
  56.         FriendsGetFriendsResponse resp = (FriendsGetFriendsResponse) client.getResponsePOJO();   
  57.         List<Friend> friends = resp.getFriend();   
  58.         return friends;   
  59.         }          
  60.     }   
  61.        
  62.     private String buildUserInfo(int id) {   
  63.          StringBuffer sb=new StringBuffer();   
  64.          sb.append("<div align=\"center\">\n");   
  65.          sb.append("图片:<xn:profile-pic uid=\"");   
  66.          sb.append(id);   
  67.          sb.append("\" linked=\"true\" size=\"tiny\"/><br>\n");   
  68.          sb.append("姓名:<xn:name uid=\""+id+"\" linked=\"true\" shownetwork=\"true\" />\n");   
  69.          sb.append("</div>\n");   
  70.          return sb.toString();   
  71.          }   
  72.                 
  73.     /**  
  74.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)  
  75.      */  
  76.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   
  77.   
  78.         response.setContentType("text/html;charset=utf-8");   
  79.         response.setCharacterEncoding("utf-8");   
  80.         response.setHeader("Charset""utf-8");   
  81.         response.setHeader("Cache-Control""no-cache");   
  82.         request.setCharacterEncoding("UTF-8");   
  83.            
  84.         JSONObject json = new JSONObject();   
  85.            
  86.         String cmd=StrCharUtil.formatNullStr(request.getParameter("cmd"));   
  87.         String callback=StrCharUtil.formatNullStr(request.getParameter("callback"));   
  88.            
  89.         String sessionKey = request.getParameter(PARAM_XN_SIG_SESSION_KEY);   
  90.            
  91.        
  92.         XiaoneiRestClient client = new XiaoneiRestClient("你的APIKey",    
  93.                 "你的Secret Key", sessionKey);   
  94.         //client.setDebug(true);   
  95.            
  96.         try{   
  97.             if("getfriends".equals(cmd)){   
  98.                 JSONArray jj = JSONArray.fromObject(getFriend(client));   
  99.                 json.put("res",jj.toString());   
  100.             }else if("myinfor".equals(cmd)){   
  101.                 int loggedInUserId = 0;   
  102.                  try {   
  103.                      loggedInUserId = client.users_getLoggedInUser();   
  104.                      EnumSet<ProfileField> enumFields = EnumSet.of(ProfileField.NAME,   
  105.                              ProfileField.HOMETOWN_LOCATION,ProfileField.BIRTHDAY,   
  106.                              ProfileField.HEADURL,ProfileField.MAINURL,   
  107.                              ProfileField.SEX,ProfileField.STAR,ProfileField.TINYURL,   
  108.                              ProfileField.ZIDOU,ProfileField.UNIVERSITY_HISTORY,   
  109.                              ProfileField.WORK_HISTORY);   
  110.                                 
  111.                      Document doc = client.users_getInfo(loggedInUserId, enumFields);   
  112.                      json.put("xml",doc.toString());   
  113.                      UsersGetInfoResponse loggedUserGetInfoRes = (UsersGetInfoResponse) client.getResponsePOJO();   
  114.                      json.put("res",JSONArray.fromObject(loggedUserGetInfoRes.getUser()));   
  115.                  }   
  116.                  catch(XiaoneiException e) {   
  117.                      e.printStackTrace();   
  118.                  }   
  119.             }else if("invite".equals(cmd)){   
  120.                 List<Integer> userIds = new ArrayList();   
  121.                 List<Friend> friends = getFriend(client);   
  122.   
  123.                 for (Friend f:friends) {   
  124.                     userIds.add(f.getId());   
  125.                 }   
  126.   
  127.                 client.requests_sendRequest(userIds);   
  128.                 request.setAttribute("uids", client.getRawResponse());   
  129.                 //进一步看看都成功邀请了哪些朋友   
  130.                 RequestsSendRequestResponse resp = (RequestsSendRequestResponse) client.getResponsePOJO();   
  131.                    
  132.                 List<Integer> uids = resp.getUid();   
  133.                    
  134.                 json.put("res",JSONArray.fromObject(uids));   
  135.             }   
  136.             if(json!=null){   
  137.                 if(callback.equals("")){ //没有回调函数   
  138.                     response.getWriter().println(json.toString());   
  139.                 }else{   
  140.                     response.setContentType("text/javascript;charset=utf-8");   
  141.                     response.getWriter().println(callback+"("+json.toString()+")");   
  142.                 }          
  143.             }   
  144.         }catch(Exception ex){   
  145.             ex.printStackTrace();   
  146.         }          
  147.        
  148.     }   
  149.   
  150.     /**  
  151.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)  
  152.      */  
  153.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {   
  154.         // TODO Auto-generated method stub   
  155.         super.doGet(request, response);   
  156.     }   
  157.   
  158. }  
package com.cxlh.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;

import com.common.utils.StrCharUtil;
import com.xiaonei.api.ProfileField;
import com.xiaonei.api.XiaoneiException;
import com.xiaonei.api.XiaoneiRestClient;
import com.xiaonei.api.schema.Friend;
import com.xiaonei.api.schema.FriendsGetFriendsResponse;
import com.xiaonei.api.schema.RequestsSendRequestResponse;
import com.xiaonei.api.schema.UsersGetInfoResponse;

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


/**
 * Servlet implementation class XN
 */
public class XN extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	public static String PARAM_XN_SIG_IN_IFRAME = "xn_sig_in_iframe";

	public static String PARAM_XN_SIG_TIME = "xn_sig_time";

	public static String PARAM_XN_SIG_ADDED = "xn_sig_added";

	public static String PARAM_XN_SIG_USER = "xn_sig_user";

	public static String PARAM_XN_SIG_SESSION_KEY = "xn_sig_session_key";

	public static String PARAM_XN_SIG_API_KEY = "xn_sig_api_key";	
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public XN() {
        super();
        // TODO Auto-generated constructor stub
    }

    private List<Friend> getFriend(XiaoneiRestClient client) throws Exception{
	    client.friends_getFriends();
	    FriendsGetFriendsResponse resp = (FriendsGetFriendsResponse) client.getResponsePOJO();
	    List<Friend> friends = resp.getFriend();
	    return friends;
	    }    	
    }
    
    private String buildUserInfo(int id) {
    	 StringBuffer sb=new StringBuffer();
    	 sb.append("<div align=\"center\">\n");
    	 sb.append("图片:<xn:profile-pic uid=\"");
    	 sb.append(id);
    	 sb.append("\" linked=\"true\" size=\"tiny\"/><br>\n");
    	 sb.append("姓名:<xn:name uid=\""+id+"\" linked=\"true\" shownetwork=\"true\" />\n");
    	 sb.append("</div>\n");
    	 return sb.toString();
    	 }
    	     
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Charset", "utf-8");
		response.setHeader("Cache-Control", "no-cache");
		request.setCharacterEncoding("UTF-8");
		
		JSONObject json = new JSONObject();
		
		String cmd=StrCharUtil.formatNullStr(request.getParameter("cmd"));
		String callback=StrCharUtil.formatNullStr(request.getParameter("callback"));
		
		String sessionKey = request.getParameter(PARAM_XN_SIG_SESSION_KEY);
		
	
	   	XiaoneiRestClient client = new XiaoneiRestClient("你的APIKey", 
	   			"你的Secret Key", sessionKey);
	   	//client.setDebug(true);
		
		try{
			if("getfriends".equals(cmd)){
				JSONArray jj = JSONArray.fromObject(getFriend(client));
				json.put("res",jj.toString());
			}else if("myinfor".equals(cmd)){
				int loggedInUserId = 0;
				 try {
					 loggedInUserId = client.users_getLoggedInUser();
					 EnumSet<ProfileField> enumFields = EnumSet.of(ProfileField.NAME,
							 ProfileField.HOMETOWN_LOCATION,ProfileField.BIRTHDAY,
							 ProfileField.HEADURL,ProfileField.MAINURL,
							 ProfileField.SEX,ProfileField.STAR,ProfileField.TINYURL,
							 ProfileField.ZIDOU,ProfileField.UNIVERSITY_HISTORY,
							 ProfileField.WORK_HISTORY);
							 
					 Document doc = client.users_getInfo(loggedInUserId, enumFields);
					 json.put("xml",doc.toString());
					 UsersGetInfoResponse loggedUserGetInfoRes = (UsersGetInfoResponse) client.getResponsePOJO();
					 json.put("res",JSONArray.fromObject(loggedUserGetInfoRes.getUser()));
				 }
				 catch(XiaoneiException e) {
					 e.printStackTrace();
				 }
			}else if("invite".equals(cmd)){
				List<Integer> userIds = new ArrayList();
				List<Friend> friends = getFriend(client);

				for (Friend f:friends) {
					userIds.add(f.getId());
				}

				client.requests_sendRequest(userIds);
				request.setAttribute("uids", client.getRawResponse());
				//进一步看看都成功邀请了哪些朋友
				RequestsSendRequestResponse resp = (RequestsSendRequestResponse) client.getResponsePOJO();
				
				List<Integer> uids = resp.getUid();
				
				json.put("res",JSONArray.fromObject(uids));
			}
			if(json!=null){
				if(callback.equals("")){ //没有回调函数
					response.getWriter().println(json.toString());
				}else{
					response.setContentType("text/javascript;charset=utf-8");
					response.getWriter().println(callback+"("+json.toString()+")");
				}		
			}
		}catch(Exception ex){
			ex.printStackTrace();
		}		
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(request, response);
	}

}

 

 最终效果见校内网:http://apps.xiaonei.com/testfaqee

你可能感兴趣的:(JavaScript,json,.net,servlet,cache)