我正在尝试使用此代码:
public static Token getAccessToken(OAuth2Config oauthDetails) {
HttpPost post = new HttpPost(oauthDetails.getTokenEndPointUrl());
String clientId = oauthDetails.getClientId();
String clientSecret = oauthDetails.getClientSecret();
String scope = oauthDetails.getScope();
List<BasicNameValuePair> parametersBody = new ArrayList<BasicNameValuePair>();
parametersBody.add(new BasicNameValuePair(OAuthConstants.GRANT_TYPE,
oauthDetails.getGrantType()));
parametersBody.add(new BasicNameValuePair(OAuthConstants.USERNAME,
oauthDetails.getUsername()));
parametersBody.add(new BasicNameValuePair(OAuthConstants.PASSWORD,
oauthDetails.getPassword()));
if (isValid(clientId)) {
parametersBody.add(new BasicNameValuePair(OAuthConstants.CLIENT_ID,
clientId));
}
if (isValid(clientSecret)) {
parametersBody.add(new BasicNameValuePair(
OAuthConstants.CLIENT_SECRET, clientSecret));
}
if (isValid(scope)) {
parametersBody.add(new BasicNameValuePair(OAuthConstants.SCOPE,
scope));
}
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse response = null;
Token accessToken = null;
try {
post.setEntity(new UrlEncodedFormEntity(parametersBody, HTTP.UTF_8));
response = client.execute(post);
int code = response.getStatusLine().getStatusCode();
if (code >= 400) {
Log.d(TAG, "Authorization server expects Basic authentication");
// Add Basic Authorization header
post.addHeader(
OAuthConstants.AUTHORIZATION,
getBasicAuthorizationHeader(oauthDetails.getUsername(),
oauthDetails.getPassword()));
Log.d(TAG, "Retry with login credentials");
try {
response.getEntity().consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = client.execute(post);
code = response.getStatusLine().getStatusCode();
if (code >= 400) {
Log.d(TAG, "Retry with client credentials");
post.removeHeaders(OAuthConstants.AUTHORIZATION);
post.addHeader(
OAuthConstants.AUTHORIZATION,
getBasicAuthorizationHeader(
oauthDetails.getClientId(),
oauthDetails.getClientSecret()));
try {
response.getEntity().consumeContent();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response = client.execute(post);
code = response.getStatusLine().getStatusCode();
if (code >= 400) {
throw new RuntimeException(
"Could not retrieve access token for user: "
+ oauthDetails.getUsername());
}
}
}
Map map = handleResponse(response);
accessToken = new Token(Long.valueOf((Integer) map.get(OAuthConstants.EXPIRES_IN)), (String) map.get(OAuthConstants.TOKEN_TYPE), (String) map.get(OAuthConstants.REFRESH_TOKEN), (String) map.get(OAuthConstants.ACCESS_TOKEN));
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return accessToken;
}
是我在我的 Android 应用程序中使用的 OAuth2Client 的一部分。我收到此错误:
android.os.NetworkOnMainThreadException
我正在阅读我应该使用 AsyncTask,但我不知道如何将此方法转换为 AsyncTask。
我会感谢一些帮助。
谢谢