1 Star 0 Fork 2

周周/vertx-examples

forked from githubsync/vertx-examples 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
TwitterOAuthExample.java 2.33 KB
一键复制 编辑 原始数据 按行查看 历史
Paulo Lopes 提交于 2017-07-14 12:15 . Fix example to be polyglot
package io.vertx.example.webclient.oauth;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.json.JsonObject;
import io.vertx.example.util.Runner;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.codec.BodyCodec;
/*
* @author <a href="mailto:akshay0007k@gmail.com">Akshay Kumar</a>
*/
public class TwitterOAuthExample extends AbstractVerticle {
// consumer key and secret are provided by twitter after registering your app.
private static final String B64_ENCODED_AUTH = "base64(your-consumer-key:your-consumer-secret)";
private static final String AUTH_URL = "https://api.twitter.com/oauth2/token";
private static final String TWEET_SEARCH_URL = "https://api.twitter.com/1.1/search/tweets.json";
// Convenience method so you can run it in your IDE
public static void main(String[] args) {
Runner.runExample(TwitterOAuthExample.class);
}
@Override
public void start() throws Exception {
// Create the web client.
WebClient client = WebClient.create(vertx);
String queryToSearch = "vertx";
// First we need to authenticate our call.
String authHeader = "Basic " + B64_ENCODED_AUTH;
client.postAbs(AUTH_URL)
.as(BodyCodec.jsonObject())
.addQueryParam("grant_type", "client_credentials")
.putHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8")
.putHeader("Authorization", authHeader)
.send(authHandler -> {
// Authentication successful.
if (authHandler.succeeded() && 200 == authHandler.result().statusCode()) {
JsonObject authJson = authHandler.result().body();
String accessToken = authJson.getString("access_token");
String header = "Bearer " + accessToken;
// Making call to search tweets.
client.getAbs(TWEET_SEARCH_URL)
.as(BodyCodec.jsonObject())
.addQueryParam("q", queryToSearch)
.putHeader("Authorization", header)
.send(handler -> {
if (handler.succeeded() && 200 == handler.result().statusCode()) {
System.out.println(handler.result().body());
} else {
System.out.println(handler.cause().getMessage());
}
});
} else { // Authentication failed
System.out.println(authHandler.cause().getMessage());
}
});
}
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zhouzq2046/vertx-examples.git
git@gitee.com:zhouzq2046/vertx-examples.git
zhouzq2046
vertx-examples
vertx-examples
4.x

搜索帮助