# Java 端到端示例 / Java end-to-end example

`OpenApiQuickStart.java` —— 一个文件跑完整流程，无任何第三方依赖。

A single self-contained file that runs the whole flow. No third-party dependencies.

## 它做了什么 / What it does

1. `GET /api/open/v1/account` —— 顺带验证签名算对了
2. `GET /api/open/v1/files/upload-url` —— 申请预签名上传地址
3. `PUT <presigned_url>` —— 直传文件到对象存储（**`Content-Type: text/plain`**）
4. `POST /api/open/v1/tasks` —— 创建任务
5. `GET /api/open/v1/tasks/{id}` —— 每 10 秒轮询，直到状态 6（完成）或 8（失败）
6. 下载 `result.zip` / `result.csv` / `activated.txt`

## 运行 / Run

需要 JDK 11 或以上。单文件源码模式，不需要先 `javac`：

Requires JDK 11+. Single-file source mode, no separate compile step:

**Windows PowerShell**（参数一定要加引号，原因见下）：

```powershell
java '-Dfile.encoding=UTF-8' OpenApiQuickStart.java
```

**cmd.exe / Linux / macOS**：

```bash
java -Dfile.encoding=UTF-8 OpenApiQuickStart.java
```

### 为什么 PowerShell 要加引号

不加引号时 PowerShell 会在**点号**处把参数拆成 `-Dfile` 和 `.encoding=UTF-8` 两段，
Java 于是把后半段当成主类名，报：

```
错误: 找不到或无法加载主类 .encoding=UTF-8
```

加上单引号（或双引号）参数就完整传过去了。cmd.exe 和 Linux/macOS 没有这个问题。

PowerShell splits the argument at the dot unless it is quoted, so Java sees
`.encoding=UTF-8` as the main class name. Quote it. Not an issue in cmd or on Unix.

### 为什么要这个参数

本文件以 UTF-8 保存，而中文版 JDK 17 及更早默认按 GBK 读源码，不加这个参数屏幕上的
中文会变成 `璐﹀彿妫€鏌` 这样的乱码。**只是显示问题，请求和结果都是对的**——
上传、创建任务、下载结果照常工作。JDK 18 起默认就是 UTF-8，可以不加。

This file is UTF-8; JDK 17 and earlier default to GBK on a Chinese-locale Windows,
which garbles console text. **Display only** — requests and results are unaffected.

### 嫌每次都要敲

在 PowerShell 里设一次环境变量，之后直接 `java OpenApiQuickStart.java` 即可
（这种写法不受上面那个拆参数问题影响）：

```powershell
$env:JAVA_TOOL_OPTIONS = '-Dfile.encoding=UTF-8'
```

运行前改文件顶部这几个常量 / Edit these constants at the top of the file first:

| 常量 | 说明 |
| --- | --- |
| `API_KEY` | 控制台生成的 API Key，同时是签名密钥 |
| `FILE_PATH` | 本地待检测文件绝对路径（纯文本，一行一条） |
| `COUNTRY` | ISO-2 国家码（`US` / `TH` / `BR`…）；邮箱、用户名类产品留空 |
| `PRODUCT_TYPE` | 任务类型 = 对外产品 ID，取自 `GET /products` |
| `BASE_URL` | API 基地址，末尾不要加斜杠 |

## Windows 路径怎么写 / Windows paths

Java 字符串里的 `\` 是转义符，所以 Windows 路径**要么用正斜杠，要么把反斜杠写成两个**。
推荐正斜杠——最不容易出错，Java 在 Windows 上同样认：

In Java string literals `\` is an escape character, so a Windows path must either use
forward slashes or doubled backslashes. Forward slashes are recommended:

```java
// 推荐：正斜杠，路径含空格也不用做任何处理
private static final String FILE_PATH = "C:/Users/dev/Downloads/Telegram Desktop/numbers.txt";

// 也可以：反斜杠写成两个
private static final String FILE_PATH = "C:\\Users\\dev\\Downloads\\Telegram Desktop\\numbers.txt";

// 编译不过：单反斜杠，报「非法转义符」（\U \d \D \T 都不是合法转义）
private static final String FILE_PATH = "C:\Users\dev\Downloads\Telegram Desktop\numbers.txt";
```

**目录名或文件名里的空格不需要任何处理**，也不要加引号——`"Telegram Desktop"` 直接写在
路径中间就行。空格只在命令行里才需要引号，Java 字符串里它就是个普通字符。
文件名里的中文同样不用管：发请求前示例会自动做 URL 编码（空格编成 `%20` 而不是 `+`）。

Spaces in folder or file names need **no** special handling and no extra quotes — write
`Telegram Desktop` as-is. Quoting is only a shell concern. Non-ASCII file names are fine
too; the example percent-encodes them before signing.

## 上传后没有结果？先看这三条 / No result after upload? Check these first

**1. `Content-Type` 必须是 `text/plain`**

预签名 URL 是按这个类型算出来的。用 `application/octet-stream`、`multipart/form-data`
或者干脆不带，对象存储会返回 `403 SignatureDoesNotMatch`——
文件其实压根没传上去，任务拿到的是一个不存在的对象键，自然没有结果。

The presigned URL is computed for this exact content type. Anything else gets
`403 SignatureDoesNotMatch` from the object storage — the file never lands, and the
task points at an object key that does not exist.

**2. 预签名 URL 只有 15 分钟有效期**

拿到就立刻上传，不要缓存复用，也不要先攒一批再传。

The presigned URL expires after 15 minutes. Upload immediately; never cache or reuse it.

**3. 上传那一步不要带四个鉴权头**

`X-Api-*` 四件套只发给我方 API。预签名 URL 自带授权信息，多带反而可能被对象存储
当作冲突签名拒绝。

The four `X-Api-*` headers go only to our API. The presigned URL already carries its
own authorization; adding them can make the object storage reject the request.

## 签名对不上？/ Signature mismatch?

签名原文五段，以 `\n` 连接，顺序不可变：

The string-to-sign is five segments joined by `\n`, in this exact order:

```
METHOD \n PATH[?QUERY] \n TIMESTAMP \n NONCE \n SHA256_HEX(body)
```

最常见的三个错 / The three most common mistakes:

- **PATH 漏了 `/api`**：要 `/api/open/v1/tasks`，不是 `/open/v1/tasks`
- **query 被重排或解码**：原样带上，不排序、不解码
- **GET 的空 body 没算摘要**：空串的 SHA-256 是 `e3b0c442…`，不是留空

另外：时间戳是**毫秒**不是秒（与服务器相差不得超过 5 分钟），
nonce 每个请求都必须不同（16~64 字符，复用会被判重放）。

Also: the timestamp is in **milliseconds**, not seconds (within 5 minutes of server
time), and the nonce must be unique per request (16–64 chars; reuse is treated as a replay).

## 生产环境请替换的两处 / Two things to replace in production

示例为了「零依赖、一个文件就能跑」手写了两个简化实现，接进你自己的项目时请换掉：

The example hand-rolls two things to stay dependency-free. Replace both in real code:

- **JSON 解析**：`jsonString` / `jsonLong` 是正则取值，只够取顶层字段 → 换 Jackson 或 Gson
- **JSON 拼装**：创建任务的请求体是手拼字符串 → 换成对象序列化

签名、上传、轮询那几段可以直接用。

The signing, upload and polling parts are fine to use as they are.
