【发布时间】:2014-08-26 01:02:15
【问题描述】:
我有以下将 FitBit 集成到 Android 的代码,它是从这个库 https://github.com/manishsri01/FitbitIntegration 中使用的,我可以获取 response.getBody() 在 webview 中显示 JSON 正文,但我希望应用程序能够自动每次运行应用程序时,无需登录并获取 OAuth 的 PIN 码即可更新代码。我能做些什么来解决这个问题?我还想将 JSON .getBody() 解析为单独的字符串变量。我怎样才能做到这一点?
MainActivity
public class MainActivity extends Activity {
OAuthService service;
Token requestToken;
// Replace these with your own api key and secret
private String apiKey = "************************";
private String apiSecret = "*************************";
private String accessToken;
private String tokenSecret;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final WebView wvAuthorize = (WebView) findViewById(R.id.wvAuthorize);
final EditText etPIN = (EditText) findViewById(R.id.etPIN);
service = new ServiceBuilder().provider(FitbitApi.class).apiKey(apiKey)
.apiSecret(apiSecret).build();
// network operation shouldn't run on main thread
new Thread(new Runnable() {
public void run() {
requestToken = service.getRequestToken();
final String authURL = service
.getAuthorizationUrl(requestToken);
// Webview nagivation should run on main thread again...
wvAuthorize.post(new Runnable() {
@Override
public void run() {
wvAuthorize.loadUrl(authURL);
}
});
}
}).start();
}
public void btnRetrieveData(View view) {
EditText etPIN = (EditText) findViewById(R.id.etPIN);
String gotPIN = etPIN.getText().toString();
final Verifier v = new Verifier(gotPIN);
// network operation shouldn't run on main thread
new Thread(new Runnable() {
public void run() {
Token accessToken = service.getAccessToken(requestToken, v);
OAuthRequest request = new OAuthRequest(Verb.GET,
"http://api.fitbit.com/1/user/-/profile.json");
service.signRequest(accessToken, request); // the access token from step
// 4
final Response response = request.send();
final TextView tvOutput = (TextView) findViewById(R.id.tvOutput);
// Visual output should run on main thread again...
tvOutput.post(new Runnable() {
@Override
public void run() {
tvOutput.setText(response.getBody());
}
});
}
}).start();
}
}
FitBitApi
public class FitbitApi extends DefaultApi10a {
private static final String AUTHORIZE_URL = "https://www.fitbit.com/oauth/authorize?oauth_token=%s";
public String getAccessTokenEndpoint() {
return "https://api.fitbit.com/oauth/access_token";
}
public String getRequestTokenEndpoint() {
return "https://api.fitbit.com/oauth/request_token";
}
public String getAuthorizationUrl(Token token) {
return String.format(AUTHORIZE_URL, token.getToken());
}
}
【问题讨论】:
-
我快速检查了他们的 api,但没有看到刷新令牌端点。如果您阅读 OAuth,您会发现这是另一种选择,而不是每次都进行完整的身份验证。不过,他们可能不会在这一轮中提供那种端点。例如,这里是 google 的 developers.google.com/accounts/docs/OAuth2WebServer#refresh
-
他们的 API 文档真的很糟糕,我上周一直在努力解决这个问题
-
看起来我会回到这个例子来展示一个彻底的答案:)
-
嗨@AndyRoid 你能指导我一下吗?我可以使用 Chrome 自定义选项卡通过 fitbit 登录。但是现在,我想从 fitbit 获取/获取用户活动的数据。我该怎么做?
标签: java android json oauth fitbit