Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save muhdkhokhar/5090272fb99789c67aa5ea985a53b5d7 to your computer and use it in GitHub Desktop.
Save muhdkhokhar/5090272fb99789c67aa5ea985a53b5d7 to your computer and use it in GitHub Desktop.
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