Appearance
Gemini API 接口 Java 方式
该模型适配于 Gemini 端侧接口标准
Base Url: https://maas-openapi.wanjiedata.com/api
获取 API KEY:https://www.wjark.com/center/api-key
使用说明
本文作为 Gemini 接口文档的 Java 版本,全文使用的 Java 版本:1.8.0_462
使用时在 PowerShell 中请依次输入以下三条命令:
切换窗口编码(解决中文乱码):chcp 65001
编译代码(指定 UTF-8 编码,解决 GBK 报错):javac -encoding UTF-8 Gemini.java
运行程序(注意:这里不要加 .java 后缀):java Gemini
本文的文件名使用的是 Gemini.Java,运行时根据实际文件名进行更改
基础文本对话
模型:gemini-2.5-flash-lite
请求示例:
Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Gemini {
public static void main(String[] args) {
// SSE 接口地址
String urlString = "https://maas-openapi.wanjiedata.com/api/v1beta/models/gemini-2.5-flash-lite:generateContent?alt=sse";
// ⚠️ 请在此处替换你的真实 API KEY
String apiKey = "$API_KEY";
String jsonPayload = "{"
+ " \"contents\": ["
+ " {"
+ " \"parts\": ["
+ " { \"text\": \"你好\" }"
+ " ]"
+ " }"
+ " ]"
+ "}";
try {
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// Java 8 配置请求
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Authorization", "Bearer "+ apiKey);
conn.setDoOutput(true);
// 发送请求体
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 获取响应
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
// 读取流式响应 (SSE)
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
String line;
System.out.println("--- 收到响应 ---");
while ((line = br.readLine()) != null) {
if (!line.trim().isEmpty()) {
System.out.println(line);
}
}
}
} else {
System.err.println("请求失败, 状态码: " + responseCode);
// 打印错误信息
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
System.err.println(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}响应示例
Java
--- 收到响应 ---
data: {"candidates": [{"content": {"role": "model","parts": [{"text": "你好"}]}}],"usageMetadata": {"trafficType": "ON_DEMAND"},"modelVersion": "gemini-2.5-flash-lite","createTime": "2026-01-13T03:53:49.426554Z","responseId": "zcFlabqEGrGhk8sPpqjBoAI"}
data: {"candidates": [{"content": {"role": "model","parts": [{"text": "!有什么"}]}}],"usageMetadata": {"trafficType": "ON_DEMAND"},"modelVersion": "gemini-2.5-flash-lite","createTime": "2026-01-13T03:53:49.426554Z","responseId": "zcFlabqEGrGhk8sPpqjBoAI"}
data: {"candidates": [{"content": {"role": "model","parts": [{"text": "可以帮到你的吗?"}]},"finishReason": "STOP"}],"usageMetadata": {"promptTokenCount": 1,"candidatesTokenCount": 9,"totalTokenCount": 10,"trafficType": "ON_DEMAND","promptTokensDetails": [{"modality": "TEXT","tokenCount": 1}],"candidatesTokensDetails": [{"modality": "TEXT","tokenCount": 9}]},"modelVersion": "gemini-2.5-flash-lite","createTime": "2026-01-13T03:53:49.426554Z","responseId": "zcFlabqEGrGhk8sPpqjBoAI"}图像分析对话
模型:gemini-2.5-flash-image-preview
请求示例:
Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class Gemini {
public static void main(String[] args) {
String urlString = "https://maas-openapi.wanjiedata.com/api/v1beta/models/gemini-2.5-flash-image-preview:generateContent";
String apiKey = "你的_API_KEY";
String imagePath = "D:\\maas-docs\\test.jpg"; // ⚠️ 修改为你的图片路径
try {
// 1. 读取图片并转换为 Base64
byte[] imageBytes = Files.readAllBytes(Paths.get(imagePath));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
// 2. 构建 JSON (Java 8 拼接方式)
String jsonPayload = "{"
+ " \"contents\": ["
+ " {"
+ " \"parts\": ["
+ " { \"text\": \"告诉我这张图片里有什么\" },"
+ " { \"inline_data\": { \"mime_type\": \"image/jpeg\", \"data\": \"" + base64Image + "\" } }"
+ " ]"
+ " }"
+ " ]"
+ "}";
// 3. 设置连接
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Authorization", 'Bearer ' + apiKey);
conn.setDoOutput(true);
// 4. 发送请求
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonPayload.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 5. 获取结果
int responseCode = conn.getResponseCode();
if (responseCode == 200) {
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
response.append(line.trim());
}
System.out.println("接口响应: " + response.toString());
}
} else {
System.err.println("错误码: " + responseCode);
// 打印错误详情
try (BufferedReader br = new BufferedReader(
new InputStreamReader(conn.getErrorStream(), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
System.err.println(line);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}响应示例
Java
接口响应: {"candidates":[{"content":{"parts":[{"text":"这张图片中有一个年轻的男子坐在厨房的台面上,他身穿灰色毛衣和深色裤子,脖子上系着一条红色的方巾。他面带微笑,看着镜头。\n\n在他的 旁边,台面上放着一大块切好的奶酪。背景是厨房,可以看到炉灶、悬挂的铜锅和窗台上的一些盆栽植物。整个画面给人一种温馨舒适的感觉。"}],"role":"model"},"finishReason":"STOP"}],"createTime":"2026-01-13T05:56:24.021162Z","model":"gemini-2.5-flash-image-preview","modelVersion":"gemini-2.5-flash-image","responseId":"iN5laaqlAdGhk8sPzYX08QU","usageMetadata":{"candidatesTokenCount":87,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":87}],"promptTokenCount":1295,"promptTokensDetails":[{"modality":"TEXT","tokenCount":5},{"modality":"IMAGE","tokenCount":1290}],"totalTokenCount":1382,"trafficType":"ON_DEMAND"}}文字生成图片
模型:gemini-3-pro-image-preview
请求示例:
Java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Gemini {
public static void main(String[] args) {
String apiUrl = "https://maas-openapi.wanjiedata.com/api/v1beta/models/gemini-3-pro-image-preview:generateContent";
String apiKey = "YOUR_API_KEY";
String jsonInputString = "{"
+ " \"contents\": ["
+ " {"
+ " \"role\": \"user\","
+ " \"parts\": ["
+ " { \"text\": \"一张赛博朋克风格的未来城市图片\" }"
+ " ]"
+ " }"
+ " ]"
+ "}";
try {
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
int code = conn.getResponseCode();
InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
StringBuilder response = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) response.append(line);
}
if (code == 200) {
// 使用简单正则提取 Base64 字符串(避免引入 JSON 库依赖)
String jsonResponse = response.toString();
Pattern pattern = Pattern.compile("\"data\":\\s*\"([^\"]+)\"");
Matcher matcher = pattern.matcher(jsonResponse);
if (matcher.find()) {
String base64Image = matcher.group(1);
byte[] imageBytes = Base64.getDecoder().decode(base64Image);
// 保存为文件
File outputFile = new File("result_image.png");
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
fos.write(imageBytes);
}
System.out.println("成功!图片已下载至: " + outputFile.getAbsolutePath());
} else {
System.out.println("未在响应中找到图片数据。");
}
} else {
System.out.println("请求失败,状态码: " + code);
System.out.println("错误详情: " + response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}Java
成功!图片已下载至: D:\maas-docs\result_image.png图片编辑
模型:gemini-3-pro-image-preview
请求示例:
Java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Gemini {
public static void main(String[] args) {
String apiUrl = "https://maas-openapi.wanjiedata.com/api/v1beta/models/gemini-3-pro-image-preview:generateContent";
String apiKey = "YOUR_API_KEY"; // 替换为你的 API Key
String inputImagePath = "input.jpg"; // 你的本地图片
String promptText = "根据这张图片生成一个类似的赛博朋克风格图像";
try {
// 1. 读取图片并转为 Base64
byte[] imageBytes = Files.readAllBytes(Paths.get(inputImagePath));
String base64Image = Base64.getEncoder().encodeToString(imageBytes);
// 2. 构造 JSON 请求体
// 注意:Java 拼接长字符串较繁琐,这里使用 String.format
String jsonInputString = "{"
+ " \"contents\": [{"
+ " \"parts\": ["
+ " { \"text\": \"" + promptText + "\" },"
+ " { \"inline_data\": { \"mime_type\": \"image/jpeg\", \"data\": \"" + base64Image + "\" } }"
+ " ]"
+ " }]"
+ "}";
// 3. 发送请求
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 4. 读取响应
int code = conn.getResponseCode();
InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
StringBuilder response = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) response.append(line);
}
if (code == 200) {
// 5. 提取并保存结果图片 (使用正则简单提取 data 字段)
String jsonResponse = response.toString();
Pattern pattern = Pattern.compile("\"data\":\\s*\"([^\"]+)\"");
Matcher matcher = pattern.matcher(jsonResponse);
if (matcher.find()) {
String outputBase64 = matcher.group(1);
byte[] outputBytes = Base64.getDecoder().decode(outputBase64);
try (FileOutputStream fos = new FileOutputStream("output_result.png")) {
fos.write(outputBytes);
}
System.out.println("成功!图片已保存至当前目录下的 output_result.png");
} else {
System.out.println("未在响应中找到图片数据,响应内容:" + jsonResponse);
}
} else {
System.out.println("HTTP 错误: " + code + ", 响应: " + response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}响应示例
Java
成功!图片已保存至当前目录下的 output_result.png音频处理
模型:gemini-2.5-pro
请求示例:
Java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class Gemini {
public static void main(String[] args) {
String apiUrl = "https://maas-openapi.wanjiedata.com/api/v1beta/models/gemini-2.5-pro:generateContent";
String apiKey = "你的API_KEY"; // <--- 替换为你的 API KEY
String audioPath = "d:/maas-docs/input.mp3";
String prompt = "这个音频文件描述了什么";
try {
// 1. 读取音频并转 Base64
byte[] audioBytes = Files.readAllBytes(Paths.get(audioPath));
String base64Audio = Base64.getEncoder().encodeToString(audioBytes);
// 2. 构造 JSON (使用 StringBuilder 避免大字符串拼接性能问题)
String jsonInput = "{\"contents\":[{\"parts\":["
+ "{\"text\":\"" + prompt + "\"},"
+ "{\"inline_data\":{\"mime_type\":\"audio/mpeg\",\"data\":\"" + base64Audio + "\"}}"
+ "]}]}";
// 3. 发送请求
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);
System.out.println("🚀 正在上传音频,请稍候...");
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 4. 读取响应
int code = conn.getResponseCode();
InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
StringBuilder response = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
}
if (code == 200) {
// 简单的正则提取 text 内容 (也可以使用 Fastjson 等库)
String resStr = response.toString();
System.out.println("\n分析结果:");
System.out.println(resStr);
} else {
System.out.println("❌ 错误码: " + code + "\n详情: " + response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}响应示例
Java
? 正在上传音频,请稍候...
分析结果:
{"candidates":[{"avgLogprobs":-3.9802398681640625,"content":{"parts":[{"text":"这段音频是一段自我介绍。\n\n一个女声说:\n\n\u003e “你好,我是万界方舟,很高兴认识你。”\n\n这听起来像是一个角色(可能来自游戏、小说或某个应用程序)或AI助手在向你问好。"}],"role":"model"},"finishReason":"STOP"}],"createTime":"2026-01-13T07:01:31.906141Z","model":"gemini-2.5-pro","modelVersion":"gemini-2.5-pro","responseId":"y-1laZ2nN8PAzwPb84agBg","usageMetadata":{"candidatesTokenCount":55,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":55}],"promptTokenCount":106,"promptTokensDetails":[{"modality":"TEXT","tokenCount":6},{"modality":"AUDIO","tokenCount":100}],"thoughtsTokenCount":1087,"totalTokenCount":1248,"trafficType":"ON_DEMAND"}}PDF 处理
模型:gemini-2.5-pro
请求示例:
Java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
public class Gemini {
public static void main(String[] args) {
String apiUrl = "https://maas-openapi.wanjiedata.com/api/v1beta/models/gemini-2.5-pro:generateContent";
String apiKey = "你的API_KEY"; // <--- 替换为你的 API KEY
String pdfPath = "d:/maas-docs/poem.pdf";
String prompt = "Can you add a few more lines to this poem?";
try {
// 1. 读取 PDF 并转 Base64
File pdfFile = new File(pdfPath);
if (!pdfFile.exists()) {
System.out.println("❌ 找不到文件: " + pdfPath);
return;
}
byte[] pdfBytes = Files.readAllBytes(Paths.get(pdfPath));
String base64Pdf = Base64.getEncoder().encodeToString(pdfBytes);
// 2. 构造 JSON (注意转义字符)
String jsonInput = "{\"contents\":[{\"parts\":["
+ "{\"text\":\"" + prompt + "\"},"
+ "{\"inline_data\":{\"mime_type\":\"application/pdf\",\"data\":\"" + base64Pdf + "\"}}"
+ "]}]}";
// 3. 发送请求
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);
System.out.println("🚀 正在上传 PDF 并分析...");
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 4. 读取响应
int code = conn.getResponseCode();
InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
StringBuilder response = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
}
if (code == 200) {
System.out.println("\n✅ 分析结果:");
// Java 8 默认不含 JSON 解析库,直接输出原始响应内容
// 实际开发建议使用 JSONObject 解析 candidates[0].content.parts[0].text
System.out.println(response.toString());
} else {
System.out.println("❌ 错误码: " + code + "\n详情: " + response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}响应示例
Java
? 正在上传 PDF 并分析...
? 分析结果:
{"candidates":[{"avgLogprobs":-1.6719720206618491,"content":{"parts":[{"text":"Of course! This is a beautiful classical-style Chinese poem about finding peace and a sense of release while walking in the mountains. The original poem sets a wonderful scene and mood.\n\nHere are a few options for additional lines that continue the theme, rhyme, and seven-character structure. I will add them to the end of the original poem.\n\nThe original poem is:\n\n**《山行》**\n石径盘云上,松风入袖凉。\n(Shí jìng pán yún shàng, sōng fēng rù xiù liáng.)\n*The stone path winds up into the clouds, the pine wind cools my sleeves.*\n\n溪声穿竹响,野鹤唳空长。\n(Xī shēng chuān zhú xiǎng, yě hè lì kōng cháng.)\n*The sound of the stream rings through the bamboo, a wild crane's cry echoes long in the sky.*\n\n忽见千峰外,一霞染夕阳。\n(Hū jiàn qiān fēng wài, yī xiá rǎn xī yáng.)\n*Suddenly, beyond a thousand peaks, I see the setting sun dyeing the clouds.*\n\n心随归鸟去,不问路何方。\n(Xīn suí guī niǎo qù, bù wèn lù hé fāng.)\n*My heart follows the returning birds, not asking which way the path leads.*\n\n---\n\n### **Option 1 (More philosophical)**\n\nThis addition expands on the final feeling of spiritual freedom and being present in the moment.\n\n**何须觅仙境,此身即徜徉。**\n(Hé xū mì xiān jìng, cǐ shēn jí cháng yáng.)\n*Why seek a mythical paradise? This very self is already wandering freely.*\n\n**The complete poem would be:**\n《山行》\n石径盘云上,松风入袖凉。\n溪 声穿竹响,野鹤唳空长。\n忽见千峰外,一霞染夕阳。\n心随归鸟去,不问路何方。\n**何须觅仙境,此身即徜徉。**\n\n---\n\n### **Option 2 (More descriptive)**\n\nThis addition describes the transition from dusk to night, continuing the vivid imagery of the mountain scene.\n\n**暮色沉群岭,清辉照我裳。**\n(Mùsè chén qún lǐng, qīng huī zhào wǒ shang.)\n*The twilight sinks over the mountain ranges, the clear moonlight shines on my clothes.*\n\n**The complete poem would be:**\n《山行》\n石径盘云上,松风入袖凉。\n溪声穿竹响,野鹤唳空长。\n忽见千峰外,一霞染夕阳。\n心随归鸟去,不问路何方。\n**暮色沉群岭,清辉照我裳。**\n\nBoth options maintain the `ang` rhyme scheme and the tranquil, transcendent mood of the original poem. I hope you like them"}],"role":"model"},"finishReason":"STOP"}],"createTime":"2026-01-13T07:10:40.664611Z","model":"gemini-2.5-pro","modelVersion":"gemini-2.5-pro","responseId":"8O9laaPIKNGhk8sPzYX08QU","usageMetadata":{"candidatesTokenCount":653,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":653}],"promptTokenCount":1301,"promptTokensDetails":[{"modality":"TEXT","tokenCount":11},{"modality":"DOCUMENT","tokenCount":1290}],"thoughtsTokenCount":4286,"totalTokenCount":6240,"trafficType":"ON_DEMAND"}}视频分析
模型:gemini-3-flash-preview
接口示例
请求示例:
Java
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
public class Gemini {
public static void main(String[] args) {
String apiUrl = "https://maas-openapi.wanjiedata.com/api/v1beta/models/gemini-3-flash-preview:generateContent";
String apiKey = "你的API_KEY"; // <--- 替换为你的 API KEY
String videoUrl = "https://example.com/test_video.mp4";
String prompt = "视频分析关键词";
try {
// 1. 构造 JSON 请求体
// 使用 String.format 方便替换变量
String jsonInput = String.format(
"{\"contents\": [{\"role\": \"user\",\"parts\": [{\"fileData\": {\"mimeType\": \"video/mp4\",\"fileUri\": \"%s\"}},{\"text\": \"%s\"}]}]}",
videoUrl, prompt
);
// 2. 发送请求
URL url = new URL(apiUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "Bearer " + apiKey);
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setDoOutput(true);
System.out.println("🚀 视频分析请求已发送,正在等待响应...");
try (OutputStream os = conn.getOutputStream()) {
byte[] input = jsonInput.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
// 3. 读取响应
int code = conn.getResponseCode();
InputStream is = (code >= 200 && code < 300) ? conn.getInputStream() : conn.getErrorStream();
StringBuilder response = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
response.append(line);
}
}
if (code == 200) {
System.out.println("\n✅ 分析结果:");
System.out.println(response.toString());
} else {
System.out.println("❌ 错误码: " + code);
System.out.println("详情: " + response.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}响应示例
Java
? 视频分析请求已发送,正在等待响应...
? 分析结果:
{"candidates":[{"content":{"parts":[{"text":"这个视频展示了一部电影或电视剧的**拍摄幕后过程(Behind the Scenes)**。\n\n具体内容可以分为以下几个部分:\n\n1. **开场特写(电影画面效果):** 视频开头展示了一个极具张力的营救画面:一名消防员从火光冲天、浓烟滚滚的车祸现场跑向镜头。背景看起来是在一个下雨的城市街道,营造出非常逼真的紧张感。\n2. **揭秘时刻:** 当导演大喊“Cut!”(停)之后,镜头后退,揭开了背后的真相。原来这个看起来真实的场景是在**影棚内**拍摄的。\n3. **绿幕与特效:** 汽车后方其实是一块巨大的**绿幕(Green Screen)**,用于后期合成城市背景和爆炸效果。现场使用了烟雾机和人工降雨设备。\n4. **演员状态:** 刚才还处于惊恐中的演员(车内的男女)在喊停后立刻露出了笑容,与消防员互动,显示出这只是表演。\n5. **拍摄剧组:** 视频最后展示了庞大的拍摄团队,包括手持摄像机的摄影师、灯光设备、吊臂摄像机以及拿着扩音器指挥的导演。\n\n**核心主题:** 视频旨在向观众展示电影工业是如何通过**实景搭建、绿幕特效和精良的拍摄技 术**,在受控的影棚环境下创造出惊险刺激的视觉奇观的。"}],"role":"model"},"finishReason":"STOP"}],"createTime":"2026-01-13T07:27:08.290842Z","model":"gemini-3-flash-preview","modelVersion":"gemini-3-flash-preview","responseId":"zPNlaZrgEYTFk7QPmomp2Qo","usageMetadata":{"candidatesTokenCount":318,"candidatesTokensDetails":[{"modality":"TEXT","tokenCount":318}],"promptTokenCount":717,"promptTokensDetails":[{"modality":"AUDIO","tokenCount":200},{"modality":"TEXT","tokenCount":5},{"modality":"VIDEO","tokenCount":512}],"thoughtsTokenCount":481,"totalTokenCount":1516,"trafficType":"ON_DEMAND"}}