Twitter dev in java

ready
1.dev.twitter.com
2.twitter4j

3.eclipse

Twitter Authentcation

OAuth , XAuth,  Base

Twitter Start my Application

1. creat a application and get the Consumer Key & Consumer secret

2. config the  twitter4j.properties. more

3. creat a class for get AccessToken & AccessToken secret and save them in your sotre

/**
	 * 
	 * @param username : username or email
	 * @param password : password
	 * @return
	 * @throws TwitterException 
	 */
    private AccessToken getAccessToken(String username, String password) throws TwitterException{
    	RequestToken rt;
        HttpClientImpl http;
        HttpResponse response;
        String resStr;
        String authorizeURL;
        HttpParameter[] params;
        AccessToken at;
        String cookie;
        http = new HttpClientImpl();
        
        rt = twitter.getOAuthRequestToken(null, "read/write");
        // trying to get an access token without permitting the request token.
        try {
            twitter.getOAuthAccessToken(rt.getToken(), rt.getTokenSecret());
        } catch (TwitterException te) {
        }
        Map<String, String> props = new HashMap<String, String>();
        response = http.get(rt.getAuthorizationURL());
        cookie = response.getResponseHeader("Set-Cookie");
//        http.setRequestHeader("Cookie", cookie);
        props.put("Cookie", cookie);
        resStr = response.asString();
        authorizeURL = catchPattern(resStr, "<form action=\"", "\" id=\"oauth_form\"");
        params = new HttpParameter[4];
        params[0] = new HttpParameter("authenticity_token"
                , catchPattern(resStr, "\"authenticity_token\" type=\"hidden\" value=\"", "\" />"));
        params[1] = new HttpParameter("oauth_token",
                catchPattern(resStr, "name=\"oauth_token\" type=\"hidden\" value=\"", "\" />"));
        params[2] = new HttpParameter("session[username_or_email]", username);
        params[3] = new HttpParameter("session[password]", password);
        response = http.request(new HttpRequest(RequestMethod.POST, authorizeURL, params, null, props));
        resStr = response.asString();
        String pin = catchPattern(resStr, "<kbd aria-labelledby=\"code-desc\"><code>", "</code></kbd>");
        at = twitter.getOAuthAccessToken(rt, pin);     
    	return at;
    }
    
    
    private static String catchPattern(String body, String before, String after) {
        int beforeIndex = body.indexOf(before);
        int afterIndex = body.indexOf(after, beforeIndex);
        return body.substring(beforeIndex + before.length(), afterIndex);
    }

 4. login with Consumer Key & Consumer secret and AccessToken & AccessToken

 5. creat a listener class for listener guys who you following.

 and now. you can anything just like in web twiiter.

any question? to [email protected]

猜你喜欢

转载自leohome.iteye.com/blog/1123064
Dev
今日推荐