有人可以帮助理解下面的代码是否有任何问题,或者可以做些什么来解决相同的问题?这些服务从 POSTMAN 工作,但通过代码出错
出现错误:
Exception and getting token :org.springframework.web.client.HttpClientErrorException: 401 Unauthorized
以下是服务代码,尝试使用 URL 编码以及 ClientId 和客户端机密编码到 base64,但没有奏效。
public class TestAPServices {
public static String ChequeIssueCheckEndPointURL = "https://Cheque.com/accounting/api/Cheque";
public static String ChequeUserID = "";
public static String ChequeUserPassword = "";
public static String ChequeIsAuthRequired = "Y";
public static String ChequeSecurityType = "OAUTH2";
public static String ChequeAccessTokenURI = "https://Cheque.com/oauth/token";
public static String ChequeGrantType = "client_credentials";
public static String ChequeClientId = "4YPC5FFFFFx0vsECzTft7Vyc6dVLdLJT";
public static String ChequeClientSecret = "gHBp7YYYaAA7HGWn";
private static void apChequeIssueCheck() throws Exception {
String url = ChequeIssueCheckEndPointURL;
String token = null;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
if ("Y".equals(ChequeIsAuthRequired) && "OAUTH2".equals(ChequeSecurityType))
token = getOauthToken();
//....
//service call
}
public static String getOauthToken() throws Exception {
try {
String url = ChequeAccessTokenURI;
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity entity = new HttpEntity(headers);
HttpEntity<String> response = null;
ResponseEntity responseEntity = null;
System.out.println("URL : " + url + "\t GrantType : " + ChequeGrantType + "\t client_id : "
+ ChequeClientId + "\t Client Secret :" + ChequeClientSecret);
url = (UriComponentsBuilder.fromHttpUrl(url)).build().encode().toUri() + "?" + Constants.GRANT_TYPE + "=" + ChequeGrantType + "&" + Constants.CLIENT_ID + "="+ Base64.byteArrayToBase64(ChequeClientId.getBytes("UTF-8"))
+ "&" + Constants.CLIENT_SECRET + "=" + Base64.byteArrayToBase64(ChequeClientSecret.getBytes("UTF-8"));
System.out.println("URL : "+ url);
response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
// failed here
//... futher code to read token
return (String) ((JSONObject) parser.parse(response.getBody())).get("access_token");
}
}
}