lzj0470 发表于 2013-1-28 09:50:34

[ java版]新浪微博之ruquest_token篇

import java.io.IOException;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URLEncoder;import java.util.ArrayList;import java.util.List;import java.util.Random;import xx.cn.weibo.Util;import weibo4j.http.HttpClient;import weibo4j.http.OAuth;import weibo4j.http.PostParameter;import weibo4j.http.Response;/** *注意项:提交参数的顺序不能改变,顺序为oauth_callback-oauth_consumer_key-oauth_nonce-oauth_signature_method-oauth_timestamp-oauth_version-source *@author loiy *@time 2011-03-25 */public class requestTokenNet extends HttpClient{private String requestUrl;private String httpMethod;private String callBackUrl;public static Random RAND = new Random();public requestTokenNet(String requestUrl,String callBackUrl,String httpMethod){this.requestUrl = requestUrl;this.httpMethod = httpMethod;this.callBackUrl = callBackUrl;}public Response getRequestToken(){int retriedCount;Response requestToken = null;      boolean bool = false;for (retriedCount = 0; retriedCount <= Util.retryCount && !bool; retriedCount++) {HttpURLConnection con = null;      OutputStream osw = null;      Response res = null;                int responseCode = -1;      try {            String Authorization = generateAuthorizationHeader(this.httpMethod,      this.requestUrl,      new PostParameter[]{new PostParameter("oauth_callback", this.callBackUrl),      new PostParameter("source",Util.APPKEY)});            con = getConnection(this.requestUrl);            con.setDoInput(true);            con.addRequestProperty("Authorization", Authorization);            con.setRequestMethod(this.httpMethod);            con.setRequestProperty("Content-Type",                     "application/x-www-form-urlencoded");            con.setDoOutput(true);            String postParam = "oauth_callback="+URLEncoder.encode(this.callBackUrl,"UTF-8")+"&source="+URLEncoder.encode(Util.APPKEY,"UTF-8");            byte[] bytes = postParam.getBytes("UTF-8");            con.setRequestProperty("Content-Length",                     Integer.toString(bytes.length));            osw = con.getOutputStream();            osw.write(bytes);            osw.flush();            osw.close();            responseCode = con.getResponseCode();            if (responseCode != 200) {                  System.out.println("getRequestToken of method is error.No-" + responseCode + " Retrying...");                } else {                bool = true;                requestToken = new Response(con);                //requestToken = res.asString();                }      }catch(Exception e){      e.printStackTrace();      }finally{      try {osw.close();//con.disconnect();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}      }}      return requestToken;}public String generateAuthorizationHeader(String method, String requestUrl, PostParameter[] params) {long timestamp = System.currentTimeMillis() / 1000;      long nonce = timestamp + RAND.nextInt();      return generateAuthorizationHeader(method, requestUrl, params, String.valueOf(nonce), String.valueOf(timestamp));}private String generateAuthorizationHeader(String method, String url, PostParameter[] params, String nonce, String timestamp) {      if (null == params) {            params = new PostParameter;      }      List<PostParameter> oauthHeaderParams = new ArrayList<PostParameter>(5);      oauthHeaderParams.add(new PostParameter("oauth_consumer_key", Util.APPKEY));      oauthHeaderParams.add(new PostParameter("oauth_signature_method",Util.OAUTH_SIGNATURE_METHOD));      oauthHeaderParams.add(new PostParameter("oauth_timestamp", timestamp));      oauthHeaderParams.add(new PostParameter("oauth_nonce", nonce));      oauthHeaderParams.add(new PostParameter("oauth_version", "1.0"));      List<PostParameter> signatureBaseParams = new ArrayList<PostParameter>(oauthHeaderParams.size() + params.length);      signatureBaseParams.addAll(oauthHeaderParams);      signatureBaseParams.addAll(OAuth.toParamList(params));                StringBuffer base = new StringBuffer(method).append("&")                .append(OAuth.encode(OAuth.constructRequestURL(url))).append("&");      String text = OAuth.encode(OAuth.normalizeRequestParameters(signatureBaseParams));                base.append(text);                String oauthBaseString = base.toString();      String signature = Util.hmacsha1(Util.APPSECRET, oauthBaseString);      oauthHeaderParams.add(new PostParameter("oauth_signature", signature));      text ="OAuth " + OAuth.encodeParameters(oauthHeaderParams, ",", true);      oauthHeaderParams.clear();      oauthHeaderParams = null;      return text;    }}
里面有些参数不能给各位看,但是可以根据办法名字就知道需要什么参数拉.如果还不知道,可以给我留言.
下面是测试:
public class xxNetTest {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubrequestTokenNet requestTokenNetTest = new requestTokenNet("http://api.t.sina.com.cn/oauth/request_token","http://localhost:8080/agriWeiBo/callback.jsp","POST");Response requestToken = requestTokenNetTest.getRequestToken();RequestToken token = null;try {token = new RequestToken(requestToken,requestTokenNetTest);} catch (WeiboException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("s="+token.getToken());}}
返回正确结果形式:
oauth_token=ad75db0a09031b04c842777398ffb73d&oauth_token_secret=f854d467045ec5131f4aae04934ce999
如果是401错误,一般都是baseString写的不对.什么是baseString,到官方去了解一下,这里不做说明,地址是:http://open.t.sina.com.cn/wiki/index.php/Oauth/request_token
页: [1]
查看完整版本: [ java版]新浪微博之ruquest_token篇