In this example we are going to see about how to use SinaWeibo OAuth2.0 using Scribe Java
SinaWeibo OAuth2.0 Example using Scribe
SinaWeibo2Example.java
01.
import
java.util.Scanner;
02.
import
com.github.scribejava.core.builder.ServiceBuilder;
03.
import
com.github.scribejava.apis.SinaWeiboApi20;
04.
import
com.github.scribejava.core.model.OAuth2AccessToken;
05.
import
com.github.scribejava.core.model.OAuthRequest;
06.
import
com.github.scribejava.core.model.Response;
07.
import
com.github.scribejava.core.model.Verb;
08.
import
com.github.scribejava.core.oauth.OAuth20Service;
09.
import
java.io.IOException;
10.
11.
public
abstract
class
SinaWeibo2Example {
12.
13.
private
static
final
String NETWORK_NAME =
"SinaWeibo"
;
14.
private
static
final
String PROTECTED_RESOURCE_URL =
"http://ift.tt/2a5OhhH"
;
15.
16.
public
static
void
main(String... args)
throws
IOException {
17.
// Replace these with your own api key and secret
18.
final
String apiKey =
"your_api_key"
;
19.
final
String apiSecret =
"your_api_secret"
;
20.
final
OAuth20Service service =
new
ServiceBuilder()
21.
.apiKey(apiKey)
22.
.apiSecret(apiSecret)
23.
.callback(
"http://ift.tt/2a0I97y"
)
24.
.build(SinaWeiboApi20.instance());
25.
final
Scanner in =
new
Scanner(System.in);
26.
27.
System.out.println(
"=== "
+ NETWORK_NAME +
"'s OAuth Workflow ==="
);
28.
System.out.println();
29.
30.
// Obtain the Authorization URL
31.
System.out.println(
"Fetching the Authorization URL..."
);
32.
final
String authorizationUrl = service.getAuthorizationUrl();
33.
System.out.println(
"Got the Authorization URL!"
);
34.
System.out.println(
"Now go and authorize ScribeJava here:"
);
35.
System.out.println(authorizationUrl);
36.
System.out.println(
"And paste the authorization code here"
);
37.
System.out.print(
">>"
);
38.
final
String code = in.nextLine();
39.
System.out.println();
40.
41.
// Trade the Request Token and Verifier for the Access Token
42.
System.out.println(
"Trading the Request Token for an Access Token..."
);
43.
final
OAuth2AccessToken accessToken = service.getAccessToken(code);
44.
System.out.println(
"Got the Access Token!"
);
45.
System.out.println(
"(if your curious it looks like this: "
+ accessToken
46.
+
", 'rawResponse'='"
+ accessToken.getRawResponse() +
"')"
);
47.
System.out.println();
48.
49.
// Now let's go and ask for a protected resource!
50.
System.out.println(
"Now we're going to access a protected resource..."
);
51.
final
OAuthRequest request =
new
OAuthRequest(Verb.GET, PROTECTED_RESOURCE_URL, service);
52.
service.signRequest(accessToken, request);
53.
final
Response response = request.send();
54.
System.out.println(
"Got it! Lets see what we found..."
);
55.
System.out.println();
56.
System.out.println(response.getCode());
57.
System.out.println(response.getBody());
58.
59.
System.out.println();
60.
System.out.println(
"Thats it man! Go and build something awesome with ScribeJava! :)"
);
61.
62.
}
63.
}
0 comments:
Post a Comment