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