腾讯微博OAuth web认证

来源:互联网 发布:审批流软件 编辑:程序博客网 时间:2024/06/05 23:56

在腾讯开放平台网站下载javaSDK,修改OAuth.java中的app和appsecret,导出jar包。

userServlet的dopost方法

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        WebOAuth weboauth=new WebOAuth();        try {            OAuth oauth=weboauth.getRequestToken();            request.getSession().setAttribute("oauth", oauth);//          weboauth.getAccessToken();            String url = "http://open.t.qq.com/cgi-bin/authorize?oauth_token="                + oauth.getOauth_token();            response.sendRedirect(url);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }


CallBackServlet的dopost方法。在获取授权之后跳转到这个servlet上,然后再这个servlet上做一些处理。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        System.out.println("1******************************");        WebOAuth weboauth=new WebOAuth();        System.out.println("2***********************************");        OAuthClient auth=new OAuthClient();        System.out.println("3********************************************");        OAuth oauth=(OAuth)request.getSession().getAttribute("oauth");        System.out.println("4*****************************************************");        oauth.setOauth_verifier(request.getParameter("oauth_verifier"));        System.out.println("5***************************************************************");        try {            oauth=auth.accessToken(oauth);        } catch (Exception e1) {            // TODO Auto-generated catch block            e1.printStackTrace();        }        System.out.println("-----------------");        System.out.println(oauth.getOauth_token());        System.out.println(oauth.getOauth_token_secret());        response.sendRedirect("http://t.qq.com/");     }


获取授权的类。OAuth构造方法需要一个一个参数,是获取授权之后跳转的页面。这里跳转的地址是上面的CallBackServlet。
//WebOAuth类package server; import com.tencent.weibo.beans.OAuth;import com.tencent.weibo.utils.OAuthClient; public class WebOAuth {    public com.tencent.weibo.beans.OAuth oauth=new com.tencent.weibo.beans.OAuth("http://localhost:8080/liecheshikebiao_qq/CallBackServlet");    OAuthClient auth=new OAuthClient();    public OAuth getRequestToken() throws Exception{        oauth = auth.requestToken(oauth);         if (oauth.getStatus() == 1) {            System.out.println("Get Request Token failed!");            return null;        } else {            String oauth_token = oauth.getOauth_token();                         return oauth;        }    }    public void getAccessToken() throws Exception{        oauth = auth.accessToken(oauth);    }}



原创粉丝点击