Created
July 19, 2024 09:47
-
-
Save muhdkhokhar/5090272fb99789c67aa5ea985a53b5d7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import okhttp3.*; | |
import com.google.gson.JsonObject; | |
import com.google.gson.JsonParser; | |
import java.io.IOException; | |
public class OAuth2TokenGenerator { | |
private static final String TOKEN_URL = "https://your-auth-server.com/oauth/token"; | |
private static final String CLIENT_ID = "your-client-id"; | |
private static final String CLIENT_SECRET = "your-client-secret"; | |
private static final String GRANT_TYPE = "client_credentials"; // or other grant types | |
private static final String SCOPE = "your-scope"; | |
public static void main(String[] args) throws IOException { | |
OkHttpClient client = new OkHttpClient(); | |
RequestBody formBody = new FormBody.Builder() | |
.add("client_id", CLIENT_ID) | |
.add("client_secret", CLIENT_SECRET) | |
.add("grant_type", GRANT_TYPE) | |
.add("scope", SCOPE) | |
.build(); | |
Request request = new Request.Builder() | |
.url(TOKEN_URL) | |
.post(formBody) | |
.build(); | |
try (Response response = client.newCall(request).execute()) { | |
if (!response.isSuccessful()) { | |
throw new IOException("Unexpected code " + response); | |
} | |
String responseBody = response.body().string(); | |
JsonObject json = JsonParser.parseString(responseBody).getAsJsonObject(); | |
String accessToken = json.get("access_token").getAsString(); | |
System.out.println("Access Token: " + accessToken); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment