我正在尝试使用客户端凭据获取 Oauth 2.0 的新访问令牌。我总是遇到禁止或未经授权的错误。虽然我可以直接登录到 url https://api.flipkart.net/oauth-service/oauth/token?grant_type=client_credentials&scope=Seller_Api并生成令牌但使用下面的代码我无法生成令牌
public static String getAccessToken(OAuth2Details oauthDetails) {
URL url;
HttpURLConnection con;
String accessToken = null;
try {
url = new URL("https://api.flipkart.net/oauth-service/oauth/token\?grant_type\=client_credentials\&scope=Seller_Api");
con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Accept", "application/json");
con.setDoOutput(true);
con.setDoInput(true);
String clientId = oauthDetails.getClientId();
String clientSecret = oauthDetails.getClientSecret();
String scope = oauthDetails.getScope();
System.out
.println("Authorization server expects Basic authentication");
con.setRequestProperty(
OAuthConstants.AUTHORIZATION,
getBasicAuthorizationHeader(oauthDetails.getClientId(),
oauthDetails.getClientSecret()));
System.out.println("Retry with client credentials");
int code = con.getResponseCode();
System.out.print(con.getResponseMessage());
BufferedReader br = new BufferedReader(new InputStreamReader(
con.getErrorStream()));
if (code == 401 || code == 403) {
String s;
while ((s = br.readLine()) != null) {
System.out.print(br.readLine());
}
con.disconnect();
System.out
.println("Could not authenticate using client credentials.");
throw new RuntimeException(
"Could not retrieve access token for client: "
+ oauthDetails.getClientId());
}
}
Map<String, String> map = handleResponse(con);
accessToken = map.get(OAuthConstants.ACCESS_TOKEN);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return accessToken;
}
public static String getBasicAuthorizationHeader(String username,
String password) {
System.out.println("uu" + OAuthConstants.BASIC + " "
+ encodeCredentials(username, password));
return OAuthConstants.BASIC + " "
+ encodeCredentials(username, password);
}
public static String encodeCredentials(String username, String password) {
String cred = username + ":" + password;
return new String(Base64.encodeBase64(cred.getBytes()));
}