Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit9c1bd23

Browse files
committed
add Google Async Example
1 parent1393131 commit9c1bd23

File tree

3 files changed

+131
-19
lines changed

3 files changed

+131
-19
lines changed

‎changelog

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
[SNAPSHOT]
2+
* add Google Async Exmaple (with bugfix for it to work)
3+
14
[2.4.0]
25
* APIs 2.0 can define different endpoints for access token and for refresh token (the same urls by default)
36
* mark Facebook doesn't support refresh token by throwing UnsupportedOperationException
Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
packagecom.github.scribejava.apis.examples;
2+
3+
importjava.util.Random;
4+
importjava.util.Scanner;
5+
importcom.github.scribejava.apis.GoogleApi20;
6+
importcom.github.scribejava.core.builder.ServiceBuilderAsync;
7+
importcom.github.scribejava.core.model.ForceTypeOfHttpRequest;
8+
importcom.github.scribejava.core.model.OAuth2AccessToken;
9+
importcom.github.scribejava.core.model.OAuthRequestAsync;
10+
importcom.github.scribejava.core.model.Response;
11+
importcom.github.scribejava.core.model.ScribeJavaConfig;
12+
importcom.github.scribejava.core.model.Verb;
13+
importcom.github.scribejava.core.oauth.OAuth20Service;
14+
importcom.ning.http.client.AsyncHttpClientConfig;
15+
importjava.util.HashMap;
16+
importjava.util.Map;
17+
importjava.util.concurrent.ExecutionException;
18+
19+
publicabstractclassGoogle20AsyncExample {
20+
21+
privatestaticfinalStringNETWORK_NAME ="G+ Async";
22+
privatestaticfinalStringPROTECTED_RESOURCE_URL ="https://www.googleapis.com/plus/v1/people/me";
23+
24+
publicstaticvoidmain(String...args)throwsInterruptedException,ExecutionException {
25+
// Replace these with your client id and secret
26+
finalStringclientId ="your client id";
27+
finalStringclientSecret ="your client secret";
28+
finalStringsecretState ="secret" +newRandom().nextInt(999_999);
29+
ScribeJavaConfig.setForceTypeOfHttpRequests(ForceTypeOfHttpRequest.FORCE_ASYNC_ONLY_HTTP_REQUESTS);
30+
finalAsyncHttpClientConfigclientConfig =newAsyncHttpClientConfig.Builder()
31+
.setMaxConnections(5)
32+
.setRequestTimeout(10_000)
33+
.setAllowPoolingConnections(false)
34+
.setPooledConnectionIdleTimeout(1_000)
35+
.setReadTimeout(1_000)
36+
.build();
37+
38+
finalOAuth20Serviceservice =newServiceBuilderAsync()
39+
.apiKey(clientId)
40+
.apiSecret(clientSecret)
41+
.scope("profile")// replace with desired scope
42+
.state(secretState)
43+
.callback("http://example.com/callback")
44+
.asyncHttpClientConfig(clientConfig)
45+
.build(GoogleApi20.instance());
46+
finalScannerin =newScanner(System.in,"UTF-8");
47+
48+
System.out.println("=== " +NETWORK_NAME +"'s OAuth Workflow ===");
49+
System.out.println();
50+
51+
// Obtain the Authorization URL
52+
System.out.println("Fetching the Authorization URL...");
53+
//pass access_type=offline to get refresh token
54+
//https://developers.google.com/identity/protocols/OAuth2WebServer#preparing-to-start-the-oauth-20-flow
55+
finalMap<String,String>additionalParams =newHashMap<>();
56+
additionalParams.put("access_type","offline");
57+
//force to reget refresh token (if usera are asked not the first time)
58+
additionalParams.put("prompt","consent");
59+
finalStringauthorizationUrl =service.getAuthorizationUrl(additionalParams);
60+
System.out.println("Got the Authorization URL!");
61+
System.out.println("Now go and authorize ScribeJava here:");
62+
System.out.println(authorizationUrl);
63+
System.out.println("And paste the authorization code here");
64+
System.out.print(">>");
65+
finalStringcode =in.nextLine();
66+
System.out.println();
67+
68+
System.out.println("And paste the state from server here. We have set 'secretState'='" +secretState +"'.");
69+
System.out.print(">>");
70+
finalStringvalue =in.nextLine();
71+
if (secretState.equals(value)) {
72+
System.out.println("State value does match!");
73+
}else {
74+
System.out.println("Ooops, state value does not match!");
75+
System.out.println("Expected = " +secretState);
76+
System.out.println("Got = " +value);
77+
System.out.println();
78+
}
79+
80+
// Trade the Request Token and Verfier for the Access Token
81+
System.out.println("Trading the Request Token for an Access Token...");
82+
OAuth2AccessTokenaccessToken =service.getAccessTokenAsync(code,null).get();
83+
System.out.println("Got the Access Token!");
84+
System.out.println("(if your curious it looks like this: " +accessToken
85+
+", 'rawResponse'='" +accessToken.getRawResponse() +"')");
86+
87+
System.out.println("Refreshing the Access Token...");
88+
accessToken =service.refreshAccessTokenAsync(accessToken.getRefreshToken(),null).get();
89+
System.out.println("Refreshed the Access Token!");
90+
System.out.println("(if your curious it looks like this: " +accessToken
91+
+", 'rawResponse'='" +accessToken.getRawResponse() +"')");
92+
System.out.println();
93+
94+
// Now let's go and ask for a protected resource!
95+
System.out.println("Now we're going to access a protected resource...");
96+
while (true) {
97+
System.out.println("Paste fieldnames to fetch (leave empty to get profile, 'exit' to stop example)");
98+
System.out.print(">>");
99+
finalStringquery =in.nextLine();
100+
System.out.println();
101+
102+
finalStringrequestUrl;
103+
if ("exit".equals(query)) {
104+
break;
105+
}elseif (query ==null ||query.isEmpty()) {
106+
requestUrl =PROTECTED_RESOURCE_URL;
107+
}else {
108+
requestUrl =PROTECTED_RESOURCE_URL +"?fields=" +query;
109+
}
110+
111+
finalOAuthRequestAsyncrequest =newOAuthRequestAsync(Verb.GET,requestUrl,service);
112+
service.signRequest(accessToken,request);
113+
finalResponseresponse =request.sendAsync(null).get();
114+
System.out.println();
115+
System.out.println(response.getCode());
116+
System.out.println(response.getBody());
117+
118+
System.out.println();
119+
}
120+
service.closeAsyncClient();
121+
}
122+
}

‎scribejava-core/src/main/java/com/github/scribejava/core/model/OAuthRequestAsync.java

Lines changed: 6 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -8,10 +8,8 @@
88
importcom.ning.http.client.ProxyServer;
99

1010
importjava.io.IOException;
11-
importjava.util.Collection;
1211
importjava.util.HashMap;
1312
importjava.util.List;
14-
importjava.util.ArrayList;
1513
importjava.util.Map;
1614
importjava.util.concurrent.Future;
1715

@@ -38,21 +36,6 @@ public OAuthRequestAsync(Verb verb, String url, OAuthService service) {
3836
super(verb,url,service);
3937
}
4038

41-
privateMap<String,Collection<String>>mapHeaders() {
42-
finalMap<String,Collection<String>>mapped =newHashMap<>();
43-
44-
for (Map.Entry<String,String>header :getHeaders().entrySet()) {
45-
finalStringheaderName =header.getKey();
46-
Collection<String>headerValues =mapped.get(headerName);
47-
if (headerValues ==null) {
48-
headerValues =newArrayList<>();
49-
mapped.put(headerName,headerValues);
50-
}
51-
headerValues.add(header.getValue());
52-
}
53-
returnmapped;
54-
}
55-
5639
public <T>Future<T>sendAsync(OAuthAsyncRequestCallback<T>callback,ResponseConverter<T>converter) {
5740
returnsendAsync(callback,converter,null);
5841
}
@@ -75,13 +58,17 @@ public <T> Future<T> sendAsync(OAuthAsyncRequestCallback<T> callback, ResponseCo
7558
boundRequestBuilder =asyncHttpClient.prepareGet(completeUrl);
7659
break;
7760
casePOST:
78-
boundRequestBuilder =asyncHttpClient.preparePost(completeUrl).setBody(getBodyContents());
61+
boundRequestBuilder =asyncHttpClient.preparePost(completeUrl)
62+
.addHeader(CONTENT_TYPE,DEFAULT_CONTENT_TYPE)
63+
.setBody(getBodyContents());
7964
break;
8065
default:
8166
thrownewIllegalArgumentException("message build error: unknown verb type");
8267
}
8368

84-
boundRequestBuilder.setHeaders(mapHeaders());
69+
for (Map.Entry<String,String>header :getHeaders().entrySet()) {
70+
boundRequestBuilder.addHeader(header.getKey(),header.getValue());
71+
}
8572

8673
if (proxyServer !=null) {
8774
boundRequestBuilder.setProxyServer(proxyServer);

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp