如何在Java中仅通过Bearer API token调用Gemini Pro模型
问题
如何在Java中仅通过(Bearer)API token作为唯一认证方式,向Gemini Pro模型发送“你能说‘你好’吗?”的请求?
背景说明
- 可通过命令
gcloud auth application-default print-access-token获取Bearer API token - 已实现常规认证方式调用Gemini Pro模型的Java代码,但需改为仅用Bearer token认证的方式
- 假设获取到的Bearer token可在未登录谷歌账号的设备上直接使用,无需账号密码
解决方案
方式一:直接调用Vertex AI REST API(无需SDK)
不依赖Vertex AI Java SDK,直接通过HTTP请求调用API,手动将Bearer token加入请求头:
import java.io.IOException; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; public class GeminiTokenAuth { public static void main(String[] args) throws IOException, InterruptedException { // 替换为你的实际参数 String bearerToken = "你的Bearer API token"; String projectId = "你的谷歌云项目ID"; String location = "us-central1"; String modelName = "gemini-pro"; // 构建API请求地址 String apiUrl = String.format( "https://%s-aiplatform.googleapis.com/v1/projects/%s/locations/%s/publishers/google/models/%s:generateContent", location, projectId, location, modelName ); // 构建请求体 String requestBody = """ { "contents": [ { "parts": [{"text": "你能说‘你好’吗?"}] } ] } """; // 发送HTTP请求 HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(apiUrl)) .header("Authorization", "Bearer " + bearerToken) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(requestBody)) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); // 输出结果 System.out.println("响应状态码: " + response.statusCode()); System.out.println("响应内容: " + response.body()); } }
方式二:修改Vertex AI SDK的认证配置
若想继续使用Vertex AI Java SDK,可通过自定义Credentials注入Bearer token:
import com.google.auth.Credentials; import com.google.cloud.vertexai.VertexAI; import com.google.cloud.vertexai.api.GenerateContentResponse; import com.google.cloud.vertexai.generativeai.preview.GenerativeModel; import com.google.cloud.vertexai.generativeai.preview.ResponseHandler; import java.io.IOException; import java.net.URI; import java.util.Collections; import java.util.List; import java.util.Map; public class GeminiSdkTokenAuth { public static void main(String[] args) throws IOException { // 替换为你的实际参数 String bearerToken = "你的Bearer API token"; String projectId = "你的谷歌云项目ID"; String location = "us-central1"; String modelName = "gemini-pro"; // 自定义Credentials,注入Bearer token Credentials customCredentials = new Credentials() { @Override public String getAuthenticationType() { return "Bearer"; } @Override public Map<String, List<String>> getRequestMetadata(URI uri) throws IOException { return Collections.singletonMap( "Authorization", Collections.singletonList("Bearer " + bearerToken) ); } @Override public boolean hasRequestMetadata() { return true; } @Override public boolean hasRequestMetadataOnly() { return true; } @Override public void refresh() throws IOException {} }; // 使用自定义Credentials初始化VertexAI客户端并调用模型 try (VertexAI vertexAI = new VertexAI(projectId, location, customCredentials)) { GenerativeModel model = new GenerativeModel(modelName, vertexAI); GenerateContentResponse response = model.generateContent("你能说‘你好’吗?"); System.out.println(ResponseHandler.getText(response)); } } }
注意事项
- Bearer token存在有效期,过期后需重新获取
- 确保你的token拥有调用Vertex AI Gemini Pro模型的权限
- 使用REST API时,需保证请求体格式符合Vertex AI API的规范
内容的提问来源于stack exchange,提问作者a.t.
相关产品推荐
相关产品推荐

