连接新浪微博oauth1 java实现

来源:互联网 发布:windows系统即将过期 编辑:程序博客网 时间:2024/05/22 06:56
package com.yeyaomai.dksns.control;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.Date;import javax.servlet.http.HttpSession;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.methods.GetMethod;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import com.yeyaomai.dksns.util.AuthUtil;import com.yeyaomai.dksns.util.Constant;/** *@author huangxiaoping */@Controllerpublic class AccessControler {private String nonce;private String oauth_timestamp;private String oauth_verifier_param;private String oauth_token_param;@RequestMapping(value="/access")public String  access(@RequestParam String oauth_verifier,@RequestParam String oauth_token,HttpSession session) throws Exception{oauth_verifier_param=oauth_verifier;oauth_token_param=oauth_token;String baseString=getBaseString();String oauth_signature=AuthUtil.hmacsha1(baseString,Constant.CONSUMER_SERCRET+"&"+session.getAttribute("oauth_token_secret"));String url=Constant.ACCESS_TOKEN_URL+"?oauth_nonce="+URLEncoder.encode(nonce, "utf-8") +"&oauth_signature_method="+URLEncoder.encode("HMAC-SHA1", "utf-8") +"&oauth_timestamp="+URLEncoder.encode(oauth_timestamp, "utf-8") +"&oauth_consumer_key="+URLEncoder.encode( Constant.OUTH_CONSUMER_KEY, "utf-8")+"&oauth_token="+oauth_token+"&oauth_verifier="+oauth_verifier+"&oauth_signature="+URLEncoder.encode( oauth_signature, "utf-8")+"&oauth_version=" +URLEncoder.encode( "1.0", "utf-8");HttpClient client=new HttpClient();GetMethod getMethod=new GetMethod(url);int statusCode=client.executeMethod(getMethod);if(200==statusCode){String response=getMethod.getResponseBodyAsString();String access_oauth_token=response.substring(12,response.indexOf("oauth_token_secret")-1);String access_oauth_token_secret=response.substring(response.indexOf("oauth_token_secret")+19,response.indexOf("user_id")-1);String userId=response.substring(response.indexOf("user_id")+8);getMethod.releaseConnection();session.setAttribute("access_oauth_token", access_oauth_token);session.setAttribute("access_oauth_token_secret", access_oauth_token_secret);session.setAttribute("userId", userId);//String userUrl=Constant.USER+"?access_token="+access_oauth_token+"&uid=hxpwangyi@163.com";String baseUserString=getUserBaseString(session);String oauth_signature_user=AuthUtil.hmacsha1(baseUserString,Constant.CONSUMER_SERCRET+"&"+access_oauth_token_secret);String userUrl="http://api.t.sina.com.cn/account/verify_credentials.json"+"?oauth_nonce="+URLEncoder.encode(nonce, "utf-8") +"&oauth_signature_method="+URLEncoder.encode("HMAC-SHA1", "utf-8") +"&oauth_timestamp="+URLEncoder.encode(oauth_timestamp, "utf-8") +"&oauth_consumer_key="+URLEncoder.encode( Constant.OUTH_CONSUMER_KEY, "utf-8")+"&oauth_token="+access_oauth_token+"&oauth_signature="+URLEncoder.encode( oauth_signature_user, "utf-8")+"&oauth_version=" +URLEncoder.encode( "1.0", "utf-8");return "redirect:"+userUrl;}return "redirect:"+"";} public String getBaseString() throws UnsupportedEncodingException {     String bss;     nonce=AuthUtil.getNonce() ;    oauth_timestamp=(new Date().getTime()+"").substring(0,10) ;    bss = "GET"+ "&"     + URLEncoder.encode(Constant.ACCESS_TOKEN_URL, "utf-8") + "&";     String bsss = "oauth_consumer_key=" + Constant.OUTH_CONSUMER_KEY + "&oauth_nonce="     +nonce + "&oauth_signature_method="     + Constant.OAUTH_SIGNATRUE_METHOD + "&oauth_timestamp="     +oauth_timestamp+"&oauth_token="+oauth_token_param+"&oauth_verifier="+oauth_verifier_param+"&oauth_version=1.0" ;     bsss = URLEncoder.encode(bsss, "utf-8");     return bss + bsss;     }   public String getUserBaseString(HttpSession session) throws UnsupportedEncodingException {     String bss;     nonce=AuthUtil.getNonce() ;    oauth_timestamp=(new Date().getTime()+"").substring(0,10) ;    bss = "GET"+ "&"     + URLEncoder.encode("http://api.t.sina.com.cn/account/verify_credentials.json", "utf-8") + "&";     String bsss = "oauth_consumer_key=" + Constant.OUTH_CONSUMER_KEY + "&oauth_nonce="     +nonce + "&oauth_signature_method="     + Constant.OAUTH_SIGNATRUE_METHOD + "&oauth_timestamp="     +oauth_timestamp+"&oauth_token="+session.getAttribute("access_oauth_token") +"&oauth_version=1.0" ;     bsss = URLEncoder.encode(bsss, "utf-8");     return bss + bsss;     } }
package com.yeyaomai.dksns.control;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.Date;import javax.servlet.http.HttpSession;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.methods.GetMethod;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.yeyaomai.dksns.util.AuthUtil;import com.yeyaomai.dksns.util.Constant;/** *@author huangxiaoping */@Controller@RequestMapping("/index")public class AuthController {private String nonce;private String oauth_timestamp;@RequestMapping(value="/auth")public String auth(HttpSession session) throws Exception{String baseString=getBaseString();String oauth_signature=AuthUtil.hmacsha1(baseString,Constant.CONSUMER_SERCRET+"&");String url="http://api.t.sina.com.cn/oauth/request_token?oauth_nonce="+URLEncoder.encode(nonce, "utf-8") +"&oauth_signature_method="+URLEncoder.encode("HMAC-SHA1", "utf-8") +"&oauth_timestamp="+URLEncoder.encode(oauth_timestamp, "utf-8") +"&oauth_consumer_key="+URLEncoder.encode( Constant.OUTH_CONSUMER_KEY, "utf-8")+"&oauth_signature="+URLEncoder.encode( oauth_signature, "utf-8")+"&oauth_callback="+URLEncoder.encode( Constant.OUTH_CALLBACK, "utf-8")+"&oauth_version=" +URLEncoder.encode( "1.0", "utf-8");HttpClient client=new HttpClient();GetMethod getMethod=new GetMethod(url);int statusCode=client.executeMethod(getMethod);if(200==statusCode){String response=getMethod.getResponseBodyAsString();String oauth_token=response.substring(12,response.indexOf("oauth_token_secret")-1);String oauth_token_secret=response.substring(response.indexOf("oauth_token_secret")+19);session.setAttribute("oauth_token_secret", oauth_token_secret);getMethod.releaseConnection();String authUrl=Constant.AUTHORIZE_URL+"?oauth_token="+oauth_token+"&oauth_callback="+Constant.OUTH_CALLBACK+"&oauth_token_secret="+oauth_token_secret;return "redirect:"+authUrl;} return "redirect:fail";} public String getBaseString() throws UnsupportedEncodingException {     String bss;     nonce=AuthUtil.getNonce() ;    oauth_timestamp=(new Date().getTime()+"").substring(0,10) ;    bss = Constant.OAUTH_REQUEST_METHOD + "&"     + URLEncoder.encode(Constant.REQUEST_TOKEN_URL, "utf-8") + "&";     String bsss ="oauth_callback="     + URLEncoder.encode(Constant.OUTH_CALLBACK, "utf-8")     + "&oauth_consumer_key=" + Constant.OUTH_CONSUMER_KEY + "&oauth_nonce="     +nonce + "&oauth_signature_method="     + Constant.OAUTH_SIGNATRUE_METHOD + "&oauth_timestamp="     +oauth_timestamp+"&oauth_version=1.0" ;     bsss = URLEncoder.encode(bsss, "utf-8");     return bss + bsss;     } }
package com.yeyaomai.dksns.util;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.util.Date;import java.util.Random;import javax.crypto.Mac;import javax.crypto.spec.SecretKeySpec;/** *@author huangxiaoping */public class AuthUtil { public static String getNonce() {     String base = "abcdefghijklmnopqrstuvwxyz0123456789";     Random random = new Random();     StringBuffer sb = new StringBuffer();     for (int i = 0; i < 43; i++) {     int number = random.nextInt(base.length());     sb.append(base.charAt(number));     }     return sb.toString(); }  public static String hmacsha1(String data, String key) {     byte[] byteHMAC = null;     try {     Mac mac = Mac.getInstance("HmacSHA1");     SecretKeySpec spec = new SecretKeySpec(key.getBytes(), "HmacSHA1");     mac.init(spec);     byteHMAC = mac.doFinal(data.getBytes());     } catch (InvalidKeyException e) {     e.printStackTrace();     } catch (NoSuchAlgorithmException ignore) {     }     String oauth = new BASE64Encoder().encode(byteHMAC);     return oauth; }  }


package com.yeyaomai.dksns.util;public class BASE64Encoder {    private static final char last2byte = (char) Integer.parseInt("00000011", 2);    private static final char last4byte = (char) Integer.parseInt("00001111", 2);    private static final char last6byte = (char) Integer.parseInt("00111111", 2);    private static final char lead6byte = (char) Integer.parseInt("11111100", 2);    private static final char lead4byte = (char) Integer.parseInt("11110000", 2);    private static final char lead2byte = (char) Integer.parseInt("11000000", 2);    private static final char[] encodeTable = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};    public BASE64Encoder() {    }    public static  String encode(byte[] from) {        StringBuffer to = new StringBuffer((int) (from.length * 1.34) + 3);        int num = 0;        char currentByte = 0;        for (int i = 0; i < from.length; i++) {            num = num % 8;            while (num < 8) {                switch (num) {                    case 0:                        currentByte = (char) (from[i] & lead6byte);                        currentByte = (char) (currentByte >>> 2);                        break;                    case 2:                        currentByte = (char) (from[i] & last6byte);                        break;                    case 4:                        currentByte = (char) (from[i] & last4byte);                        currentByte = (char) (currentByte << 2);                        if ((i + 1) < from.length) {                            currentByte |= (from[i + 1] & lead2byte) >>> 6;                        }                        break;                    case 6:                        currentByte = (char) (from[i] & last2byte);                        currentByte = (char) (currentByte << 4);                        if ((i + 1) < from.length) {                            currentByte |= (from[i + 1] & lead4byte) >>> 4;                        }                        break;                }                to.append(encodeTable[currentByte]);                num += 6;            }        }        if (to.length() % 4 != 0) {            for (int i = 4 - to.length() % 4; i > 0; i--) {                to.append("=");            }        }        return to.toString();    }}



package com.yeyaomai.dksns.util;/** *@author huangxiaoping */public class Constant {public static final String OAUTH_REQUEST_METHOD="GET";public static final String REQUEST_TOKEN_URL="http://api.t.sina.com.cn/oauth/request_token";public static final String OUTH_CALLBACK="http://www.open.cn:8080/access";public static final String OUTH_CONSUMER_KEY="2716873751";public static final String OAUTH_SIGNATRUE_METHOD="HMAC-SHA1";public static final String AUTHORIZE_URL="http://api.t.sina.com.cn/oauth/authorize";public static final String ACCESS_TOKEN_URL="http://api.t.sina.com.cn/oauth/access_token";public static final String CONSUMER_SERCRET="641c8b41d7809857fbbe4f946a719326";public static final String USER="https://api.weibo.com/2/users/show.json";}

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:jee="http://www.springframework.org/schema/jee"    xmlns:mvc="http://www.springframework.org/schema/mvc"     xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:context="http://www.springframework.org/schema/context"    xmlns:p="http://www.springframework.org/schema/p"    xsi:schemaLocation="http://www.springframework.org/schema/beans     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd     http://www.springframework.org/schema/tx     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd     http://www.springframework.org/schema/jee     http://www.springframework.org/schema/jee/spring-jee-3.0.xsd     http://www.springframework.org/schema/context     http://www.springframework.org/schema/context/spring-context-3.0.xsd    http://www.springframework.org/schema/mvc     http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"    default-autowire="byName">   <context:component-scan base-package="com.yeyaomai.dksns.*"></context:component-scan><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" lazy-init="false"/>              <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />          <mvc:annotation-driven />    <mvc:resources mapping="/resources/**" location="/resources/" /><bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass"><value>org.springframework.web.servlet.view.JstlView</value></property> <property name="prefix"><value>/WEB-INF/views/</value></property> <property name="suffix"><value>.jsp</value></property> </bean>                <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />                 </beans>





原创粉丝点击