Java OAuth 2.0 通过 HTTP GET 获取带有客户端 ID 和密钥的访问令牌

huangapple 未分类评论41阅读模式
英文:

Java OAuth 2.0 Acquire access token via HTTP GET with client Id and secret

问题

private String setAccessTokenByClientIdAndSecret() throws Exception {
    String accessToken = "";
    try {
        StringBuilder sb = new StringBuilder("grant_type=client_credentials");
        sb.append("&client_id=").append(msdOauthClientId).append("&client_secret=").append(msdOauthSecret);

        URL url = new URL(msdOathUrl + "?" + sb.toString());
        HttpURLConnection endPointRequestConnection = (HttpURLConnection) url.openConnection();
        endPointRequestConnection.setRequestMethod("GET");
        endPointRequestConnection.setRequestProperty("Accept", "application/json"); // Set Accept header to indicate JSON response
        endPointRequestConnection.setInstanceFollowRedirects(false);

        if (endPointRequestConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new Exception("Error in obtaining an access token. " + endPointRequestConnection.getResponseMessage());
        }

        InputStream tokenRequestStream = endPointRequestConnection.getInputStream();
        
        // Read JSON response using appropriate libraries (e.g., Jackson or Gson)
        BufferedReader reader = new BufferedReader(new InputStreamReader(tokenRequestStream));
        StringBuilder responseBuilder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            responseBuilder.append(line);
        }

        JSONObject tokenRequestResult = new JSONObject(responseBuilder.toString());
        accessToken = tokenRequestResult.getString("access_token");
    } catch (Exception e) {
        // Handle exceptions appropriately
    }
    return accessToken;
}

请注意,我已经在代码中进行了以下更改:

  1. grant_type 的拼写从 "Grant_type=client_credentials" 更改为 "grant_type=client_credentials"
  2. &Client_Id= 更改为 &client_id=,将 &Client_secret= 更改为 &client_secret=
  3. endPointRequestConnection.setRequestProperty("Content-Type", "multipart/form-data"); 更改为 endPointRequestConnection.setRequestProperty("Accept", "application/json");,以表明需要 JSON 格式的响应。
  4. 添加了对 JSON 响应的适当处理,使用类似 Jackson 或 Gson 的库来解析 JSON 数据。

请注意,你需要根据你的项目的实际需求,导入适当的库以进行 JSON 数据的解析。以上代码片段应该可以帮助你从 HTTP 响应中获取访问令牌,并且期望响应是 JSON 格式的。

英文:

I want to retrieve with Java 1.6 an access token by usinig HTTP method GET, client Id and secret.

I am using the below code to make it work, but the response i receive is a generic html page instead of the json response with the tokens in it.

Can you please check the code for any mistakes I have made?

Thank you in advance.

private String setAccessTokenByClientIdAndSecret() throws Exception {
    String accessToken = "";
	try {
		StringBuilder sb = null;
        sb = new StringBuilder("Grant_type=client_credentials");
	        sb.append("&Client_Id=").append(msdOauthClientId).append("&Client_secret=").append(msdOauthSecret).append("&Resource=").append(msdOauthResourceUrl);				
	        		
	        URL url = new URL(msdOathUrl+"?"+sb.toString());
	        HttpURLConnection endPointRequestConnection = (HttpURLConnection) url.openConnection();           
	        endPointRequestConnection.setRequestMethod("GET");
	        endPointRequestConnection.setRequestProperty("Content-Type", "multipart/form-data"); 
	        endPointRequestConnection.setInstanceFollowRedirects(false);	

	        if (endPointRequestConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
                throw new Exception("Error in obtaining an access token. " + endPointRequestConnection.getResponseMessage());
	        }
	
	        InputStream tokenRequestStream = endPointRequestConnection.getInputStream();
			
	        JSONObject tokenRequestResult = new JSONObject(tokenRequestStream);
	        accessToken = (String) tokenRequestResult.get("access_token");
	} catch (Exception e) {

	}return accessToken;
}

huangapple
  • 本文由 发表于 2020年7月25日 01:13:42
  • 转载请务必保留本文链接:https://java.coder-hub.com/63078387.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定