### Example Authorization Header Value Source: https://tengxunfanyi.apifox.cn/doc-1404536 An example of the complete Authorization header value, formatted according to the specified structure with placeholder values for SecretId and Signature. ```plaintext TC3-HMAC-SHA256 Credential=AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host, Signature=2230eefd229f582d8b1b891af7107b91597240707d778ab3738f756258d7652c ``` -------------------------------- ### Full API Request Example Source: https://tengxunfanyi.apifox.cn/doc-1404536 A complete example of an HTTP POST request to a Tencent Cloud API, including the Authorization header and the request body. This demonstrates how the signature is used in a real API call. ```http POST https://cvm.tencentcloudapi.com/ Authorization: TC3-HMAC-SHA256 Credential=AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host, Signature=2230eefd229f582d8b1b891af7107b91597240707d778ab3738f756258d7652c Content-Type: application/json; charset=utf-8 Host: cvm.tencentcloudapi.com X-TC-Action: DescribeInstances X-TC-Version: 2017-03-12 X-TC-Timestamp: 1551113065 X-TC-Region: ap-guangzhou {"Limit": 1, "Filters": [{"Values": ["\u672a\u547d\u540d"], "Name": "instance-name"}]} ``` -------------------------------- ### Example String to Sign Source: https://tengxunfanyi.apifox.cn/doc-1404536 An example of the final string to sign based on the provided parameters. This string is used as input for the HMAC-SHA256 hashing function. ```plaintext TC3-HMAC-SHA256 1551113065 2019-02-25/cvm/tc3_request 5ffe6a04c0664d6b969fab9a13bdab201d63ee709638e2749d62a09ca18d7031 ``` -------------------------------- ### Tencent Translation API - Calling Methods Source: https://tengxunfanyi.apifox.cn/doc-1404174 Guides on how to structure API requests, including common parameters and signature generation. ```APIDOC ## API Calling Methods ### Request Structure Requests are typically made using HTTP POST with a JSON payload. ### Common Parameters - **AppId** (string): Your application ID. - **Timestamp** (integer): The current Unix timestamp. - **Nonce** (string): A random string to prevent replay attacks. - **Signature** (string): The generated signature for the request. ### Signature Method v3 (Example) Signatures are generated using a specific algorithm involving common parameters and your secret key. The exact method involves sorting parameters and then applying an HMAC-SHA1 or similar hashing function. ``` // Pseudo-code for signature generation function generateSignature(params, secretKey) { // 1. Sort parameters alphabetically by key. let sortedParams = sortObjectKeys(params); // 2. Concatenate parameter key-value pairs into a string. let paramString = ""; for (key in sortedParams) { paramString += key + sortedParams[key]; } // 3. Prepend the secret key to the parameter string. let stringToSign = secretKey + paramString; // 4. Compute the signature using HMAC-SHA1 (or specified algorithm). let signature = hmacSha1(stringToSign, secretKey); return signature; } ``` ### Return Results Responses are returned in JSON format, containing the translation results or error information. ### Parameter Types - Strings: UTF-8 encoded. - Integers: Standard integer types. - Timestamps: Unix epoch time. ``` -------------------------------- ### TC3-HMAC-SHA256 Authentication Example Source: https://tengxunfanyi.apifox.cn/doc-1404536 Demonstrates how to construct a signed API request to Tencent Cloud using the TC3-HMAC-SHA256 algorithm. Includes example code in Golang, PHP, and Ruby. ```APIDOC ## POST / ### Description This endpoint shows how to make a request to the Tencent Cloud CVM service using TC3-HMAC-SHA256 authentication. It includes steps for building the canonical request, string to sign, signature, and authorization header. ### Method POST ### Endpoint https://cvm.tencentcloudapi.com/ ### Parameters #### Request Body - **Limit** (integer) - Optional - Maximum number of instances to return. - **Filters** (array) - Optional - Filters to apply to the instance list. - **Values** (array) - Optional - Filter values. - **Name** (string) - Optional - Filter name. ### Request Example ```json { "Limit": 1, "Filters": [{ "Values": ["\u672a\u547d\u540d"], "Name": "instance-name" }] } ``` ### Response #### Success Response (200) This example focuses on request construction and signing, so the specific response structure depends on the actual API called (DescribeInstances in this case). #### Response Example ```json { "Response": { "TotalCount": 0, "InstanceSet": [], "RequestId": "..." } } ``` ``` -------------------------------- ### Tencent Translation API - API Overview Source: https://tengxunfanyi.apifox.cn/doc-1404536 Provides a high-level overview of the Tencent Translation API, including its capabilities, supported features, and general usage guidelines. It acts as a starting point for understanding the API's functionality. ```APIDOC ## Tencent Translation API - API Overview ### Description This section provides a general introduction to the Tencent Translation API, outlining its core functionalities and benefits. It serves as a starting point for users to understand what the API offers. ### Key Features - Supports various translation types: Text, Image, Speech, and File Translation. - Includes language detection capabilities. - Offers robust error handling and data structures. ### Usage Guidelines - All API requests must be authenticated using security credentials and a valid signature. - Refer to the 'Signature Method v3' documentation for detailed authentication steps. - Consult specific API interface documentation for request parameters and response formats. ### Related Sections - Data Structures - Error Codes - API Interfaces (Text Translation, Image Translation, etc.) ``` -------------------------------- ### Derive Signing Key Source: https://tengxunfanyi.apifox.cn/doc-1404536 This pseudocode demonstrates the process of deriving the final signing key by applying HMAC-SHA256 iteratively. It starts with the SecretKey and uses specific inputs for each step. ```pseudocode SecretKey = "Gu5t9xGARNpq86cd98joQYCN3*******" SecretDate = HMAC_SHA256("TC3" + SecretKey, Date) SecretService = HMAC_SHA256(SecretDate, Service) SecretSigning = HMAC_SHA256(SecretService, "tc3_request") ``` -------------------------------- ### Signature Process Overview Source: https://tengxunfanyi.apifox.cn/doc-1404536 This section provides an overview of the signature generation process, including steps like constructing the request string, calculating the signature, and assembling the `Authorization` header. ```APIDOC ## Signature Process Overview Understanding the signature process is crucial for authenticating API requests. Follow these steps to generate a valid signature. ### Steps for Signature Generation 1. **Construct Canonical Request String**: Create a standardized string representation of your API request. 2. **Construct String to Sign**: Formulate the string that will be used as input for the signing algorithm. 3. **Calculate Signature**: Compute the signature using the designated algorithm (e.g., HMAC-SHA1 or HMAC-SHA256) with your `SecretKey`. 4. **Construct Authorization Header**: Assemble the final `Authorization` header, typically including the access key ID, signed headers, and the calculated signature. ``` -------------------------------- ### Tencent Cloud API v1 GET Request Structure Source: https://tengxunfanyi.apifox.cn/doc-1404517 示例展示了使用签名方法 v1 的腾讯云 API GET 请求结构,包含了请求 URL、Host 和 Content-Type 等关键信息。此结构是向腾讯云服务器发送查询实例列表等操作请求的基础。 ```http https://cvm.tencentcloudapi.com/?Action=DescribeInstances&Version=2017-03-12&SignatureMethod=HmacSHA256&Timestamp=1527672334&Signature=37ac2f4fde00b0ac9bd9eadeb459b1bbee224158d66e7ae5fcadb70b2d181d02&Region=ap-guangzhou&Nonce=23823223&SecretId=AKID********EXAMPLE Host: cvm.tencentcloudapi.com Content-Type: application/x-www-form-urlencoded ``` -------------------------------- ### 文本翻译 Source: https://tengxunfanyi.apifox.cn/doc-1404999 支持对文本内容进行翻译,可以指定源语言和目标语言。 ```APIDOC ## POST /api/translate/text ### Description Performs text translation between specified source and target languages. ### Method POST ### Endpoint /api/translate/text ### Parameters #### Request Body - **text** (string) - Required - The text content to be translated. - **source** (string) - Optional - The source language code (e.g., 'en', 'zh'). If not provided, auto-detection is used. - **target** (string) - Required - The target language code (e.g., 'fr', 'es'). ### Request Example ```json { "text": "Hello, world!", "source": "en", "target": "zh" } ``` ### Response #### Success Response (200) - **translatedText** (string) - The translated text content. - **detectedSourceLanguage** (string) - The detected source language code if 'source' was not provided. #### Response Example ```json { "translatedText": "你好,世界!", "detectedSourceLanguage": "en" } ``` ``` -------------------------------- ### 腾讯翻译 API v3 签名 - GET 请求示例 Source: https://tengxunfanyi.apifox.cn/doc-1404517 展示了使用腾讯翻译 API v3 签名方法的 HTTP GET 请求结构,包括 URL、必需的 HTTP Header(如 Authorization, Content-Type, Host, X-TC-Action, X-TC-Version, X-TC-Timestamp, X-TC-Region)以及示例参数。 ```http https://cvm.tencentcloudapi.com/?Limit=10&Offset=0 Authorization: TC3-HMAC-SHA256 Credential=AKID********EXAMPLE/2018-10-09/cvm/tc3_request, SignedHeaders=content-type;host, Signature=5da7a33f6993f0614b047e5df4582db9e9bf4672ba50567dba16c6ccf174c474 Content-Type: application/x-www-form-urlencoded Host: cvm.tencentcloudapi.com X-TC-Action: DescribeInstances X-TC-Version: 2017-03-12 X-TC-Timestamp: 1539084154 X-TC-Region: ap-guangzhou ``` -------------------------------- ### 语音翻译 Source: https://tengxunfanyi.apifox.cn/doc-1404999 支持对语音内容进行翻译,需要提供音频文件或音频流。 ```APIDOC ## POST /api/translate/voice ### Description Translates spoken language into text in a specified target language. ### Method POST ### Endpoint /api/translate/voice ### Parameters #### Request Body - **audioContent** (string) - Required - Base64 encoded audio content. - **source** (string) - Optional - The source language code (e.g., 'en', 'zh'). If not provided, auto-detection is used. - **target** (string) - Required - The target language code (e.g., 'fr', 'es'). ### Request Example ```json { "audioContent": "base64_encoded_audio_data...", "source": "en", "target": "zh" } ``` ### Response #### Success Response (200) - **translatedText** (string) - The translated text from the speech. - **detectedSourceLanguage** (string) - The detected source language code if 'source' was not provided. #### Response Example ```json { "translatedText": "你好,世界!", "detectedSourceLanguage": "en" } ``` ``` -------------------------------- ### Generate Tencent Cloud API Signature - Python Source: https://tengxunfanyi.apifox.cn/doc-1404838 Provides a Python script to generate signatures for Tencent Cloud API 3.0. It uses the `hmac` and `hashlib` modules for signing and `requests` for making API calls. Requires installation of the `requests` library (`pip install requests`). ```python # -*- coding: utf8 -*- import base64 import hashlib import hmac import time import requests secret_id = "AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******" secret_key = "Gu5t9xGARNpq86cd98joQYCN3*******" def get_string_to_sign(method, endpoint, params): s = method + endpoint + "/?" query_str = "&".join("%s=%s" % (k, params[k]) for k in sorted(params)) return s + query_str def sign_str(key, s, method): hmac_str = hmac.new(key.encode("utf8"), s.encode("utf8"), method).digest() return base64.b64encode(hmac_str) if __name__ == '__main__': endpoint = "cvm.tencentcloudapi.com" data = { 'Action' : 'DescribeInstances', 'InstanceIds.0' : 'ins-09dx96dg', 'Limit' : 20, 'Nonce' : 11886, 'Offset' : 0, 'Region' : 'ap-guangzhou', 'SecretId' : secret_id, 'Timestamp' : 1465185768, # int(time.time()) 'Version': '2017-03-12' } s = get_string_to_sign("GET", endpoint, data) data["Signature"] = sign_str(secret_key, s, hashlib.sha1) print(data["Signature"]) # 此处会实际调用,成功后可能产生计费 # resp = requests.get("https://" + endpoint, params=data) # print(resp.url) ``` -------------------------------- ### Tencent Translation API - Overview Source: https://tengxunfanyi.apifox.cn/doc-1404415 General information about the Tencent Translation API, including request limits, common questions, and product details. ```APIDOC ## Tencent Translation API ### Description Provides access to Tencent's advanced translation services, supporting various content types and offering high accuracy and efficiency. ### Key Features: - Text Translation - Image Translation - Speech Translation - File Translation - Language Identification ### Request Limits: - **QPS Limit:** - Text Translation, Speech Translation, Language Identification: 5 requests/second per interface. - Image Translation: 1 request/second per interface. - **Character Limit:** Max 2000 characters per request. - **Image Limit:** JPG format, max 1MB, clear text. - **Speech Limit:** PCM, MP3, AMR formats, max 1MB per file, max 40KB per chunk. ``` -------------------------------- ### Tencent Translation API Overview Source: https://tengxunfanyi.apifox.cn/doc-1404174 Overview of the Tencent Translation API, including product details, advantages, and application scenarios. ```APIDOC ## Tencent Translation API ### Description Provides a comprehensive suite of translation services including text, image, speech, and file translation. It is designed for high-quality, efficient, and scalable translation needs. ### Product Overview The Tencent Translation API (TMT) offers advanced machine translation capabilities. ### Product Advantages - High accuracy and fluency - Support for multiple languages - Real-time translation for various content types - Scalable and reliable infrastructure ### Application Scenarios - Cross-border communication - Content localization - Customer support - Global information access ``` -------------------------------- ### POST /FileTranslate Result Query Source: https://tengxunfanyi.apifox.cn/api-39780070 Retrieves the result of a file translation request. Supports callback or polling methods to get the translation status and data. ```APIDOC ## POST /FileTranslate Result Query ### Description Retrieves the result of a file translation request. Users can choose between callback or polling to obtain the translation outcome. The endpoint has a rate limit of 20 requests per second. ### Method POST ### Endpoint https://tmt.tencentcloudapi.com ### Parameters #### Header Parameters - **X-TC-Action** (string) - Required - The name of the API operation. For this endpoint, it is `GetFileTranslate`. - **X-TC-Timestamp** (integer) - Required - The current UNIX timestamp indicating when the API request was made. For example, `1529223702`. Note: A difference of more than 5 minutes from the server time may cause a signature expiration error. - **X-TC-Version** (string) - Required - The version of the API. For this endpoint, it is `2018-03-21`. - **Authorization** (string) - Required - The HTTP standard authentication header field (e.g., `TC3-HMAC-SHA256 Credential=AKIDEXAMPLE/Date/service/tc3_request, SignedHeaders=content-type;host, Signature=fe5f80f77d5fa3beca038a248ff027d0445342fe2855ddc963176630326f1024`). - **X-TC-Token** (string) - Optional - The token from the temporary security credentials issued by the security credential service. When using this, SecretId and SecretKey should be replaced with TmpSecretId and TmpSecretKey from the temporary credentials. This field cannot be set when using long-term keys. - **X-TC-Language** (string) - Optional - Specifies the language of the API response. Only supported by some interfaces. Values: `zh-CN` for Chinese, `en-US` for English. Default is `zh-CN`. #### Request Body - **TaskId** (string) - Required - The task ID for the file translation. ### Request Example ```json { "TaskId": "100001" } ``` ### Response #### Success Response (200) - **Data** (object) - Contains the translation result details. - **Status** (string) - The current status of the translation task (e.g., `Wait`, `Processing`, `Success`, `Failed`). - **FileData** (string) - The translated file content (if available). - **TaskId** (string) - The task ID. - **Message** (string) - Any message or error description related to the task. - **Progress** (string) - The progress of the translation task (e.g., `80`). - **RequestId** (string) - A unique ID for the request, used for troubleshooting. #### Response Example ```json { "Response": { "Data": { "Status": "Wait", "FileData": "", "TaskId": "100001", "Message": "", "Progress": "80" }, "RequestId": "xx" } } ``` ### Error Codes - **FailedOperation**: Operation failed. (Other common error codes are detailed in Public Error Codes.) ``` -------------------------------- ### Tencent Translation API - Overview Source: https://tengxunfanyi.apifox.cn/doc-1404992 This section provides a general overview of the Tencent Translation API, including product details, advantages, and application scenarios. ```APIDOC ## Tencent Translation API Overview ### Description Provides an overview of the Tencent Translation API, its benefits, and use cases. ### Key Features - Supports Text Translation, Voice Translation, and Image Translation. - Offers high accuracy and supports multiple languages. - Suitable for various applications including real-time translation and document translation. ### Supported Languages - Text Translation: Chinese, English, Japanese, Korean, French, Spanish, Italian, German, Turkish, Russian, Portuguese, Vietnamese, Indonesian, Malay, Thai. - Voice Translation: Chinese and English (bidirectional). - Image Translation: Chinese and English (bidirectional). ``` -------------------------------- ### 腾讯翻译 API 语种识别请求 (Swift) Source: https://tengxunfanyi.apifox.cn/api-39786791 使用 Swift 调用腾讯翻译 API 进行语种识别。展示了如何构建请求和处理响应。 ```Swift import Foundation func detectLanguageSwift(text: String, projectId: Int) { guard let url = URL(string: "https://tmt.tencentcloudapi.com") else { print("Invalid URL") return } var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("LanguageDetect", forHTTPHeaderField: "X-TC-Action") request.setValue("", forHTTPHeaderField: "X-TC-Region") // 根据需要填写 request.setValue(String(Int(Date().timeIntervalSince1970)), forHTTPHeaderField: "X-TC-Timestamp") request.setValue("2018-03-21", forHTTPHeaderField: "X-TC-Version") request.setValue("", forHTTPHeaderField: "Authorization") // 填写签名 request.setValue("zh-CN", forHTTPHeaderField: "X-TC-Language") request.setValue("application/json", forHTTPHeaderField: "Content-Type") let body: [String: Any] = [ "Text": text, "ProjectId": projectId ] guard let httpBody = try? JSONSerialization.data(withJSONObject: body, options: []) else { print("Failed to serialize JSON") return } request.httpBody = httpBody let session = URLSession.shared let task = session.dataTask(with: request) { data, response, error in if let error = error { print("Error: \(error)") return } if let httpResponse = response as? HTTPURLResponse { if let data = data, let responseString = String(data: data, encoding: .utf8) { print("Response: \(responseString)") } } } task.resume() } // 调用示例: // detectLanguageSwift(text: "hello", projectId: 0) ``` -------------------------------- ### Successful API Response Example (JSON) Source: https://tengxunfanyi.apifox.cn/api-39791671 This JSON object represents a successful response from the Tengxunfanyi API. It includes a RequestId for tracking, the source and target languages, and a list of translated texts. ```json { "Response": { "RequestId": "beb15bd7-29aa-4f0f-9a80-574d6fc3733f", "Source": "zh", "Target": "en", "TargetTextList": [ "Hello.", "What's the weather like today?" ] } } ``` -------------------------------- ### API Overview Source: https://tengxunfanyi.apifox.cn/doc-1404440 General information about the Tencent Translation API, including its introduction, advantages, and application scenarios. ```APIDOC ## Tencent Translation API Overview ### Description Welcome to the Machine Translation API 3.0 version. The new API interface documentation is more standardized and comprehensive, with unified parameter styles and common error codes. It supports all regions for nearby access, allowing you to connect to Tencent Cloud products faster. For more Tencent Cloud API 3.0 usage introductions, please refer to: Quick Start. Tencent Machine Translation (Tencent Machine Translation) combines the advantages of neural machine translation and statistical machine translation, automatically learning translation knowledge from large-scale bilingual corpus to realize automatic translation from source language text to target language text. Currently, it supports text mutual translation between Chinese and English, Japanese, and Korean. ``` -------------------------------- ### 批量文本翻译 Source: https://tengxunfanyi.apifox.cn/doc-1404999 支持同时对多个文本内容进行翻译。 ```APIDOC ## POST /api/translate/batch ### Description Performs batch translation for multiple text segments. ### Method POST ### Endpoint /api/translate/batch ### Parameters #### Request Body - **texts** (array) - Required - An array of text objects, each with 'text' and optional 'source' and 'target' fields. - **text** (string) - Required - The text content to translate. - **source** (string) - Optional - The source language code. - **target** (string) - Required - The target language code. ### Request Example ```json { "texts": [ { "text": "Hello", "source": "en", "target": "zh" }, { "text": "Thank you", "source": "en", "target": "fr" } ] } ``` ### Response #### Success Response (200) - **translations** (array) - An array of translation results, corresponding to the input texts. - **translatedText** (string) - The translated text. - **detectedSourceLanguage** (string) - The detected source language. #### Response Example ```json { "translations": [ { "translatedText": "你好", "detectedSourceLanguage": "en" }, { "translatedText": "Merci", "detectedSourceLanguage": "en" } ] } ``` ``` -------------------------------- ### Python Signature Generation Source: https://tengxunfanyi.apifox.cn/doc-1404838 This section provides a Python code example that demonstrates how to generate a signature for Tencent Cloud API 3.0 requests. It covers the necessary steps for preparing parameters, calculating the signature using HMAC-SHA1, and constructing the request. ```APIDOC ## GET cvm.tencentcloudapi.com ### Description This example demonstrates how to generate a signature for a Tencent Cloud API 3.0 request using Python. It shows how to construct the string to sign, apply the HMAC-SHA1 algorithm with Base64 encoding for the signature, and prepare the request parameters. ### Method GET ### Endpoint `https://cvm.tencentcloudapi.com/ ### Parameters #### Path Parameters None #### Query Parameters - **Action** (string) - Required - The name of the API action to perform (e.g., `DescribeInstances`). - **InstanceIds.0** (string) - Required - The ID of the instance to describe. - **Limit** (integer) - Optional - The maximum number of instances to return. - **Nonce** (integer) - Required - A random nonce value. - **Offset** (integer) - Optional - The starting offset for paginating results. - **Region** (string) - Required - The region to which the request is made. - **SecretId** (string) - Required - Your Tencent Cloud API access key ID. - **Timestamp** (integer) - Required - The Unix timestamp for the request. - **Version** (string) - Required - The API version to use (e.g., `2017-03-12`). - **Signature** (string) - Required - The generated signature for the request. ### Request Example ```python # -*- coding: utf8 -*- import base64 import hashlib import hmac import time import requests secret_id = "AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******" secret_key = "Gu5t9xGARNpq86cd98joQYCN3*******" def get_string_to_sign(method, endpoint, params): s = method + endpoint + "/?" query_str = "&".join("%s=%s" % (k, params[k]) for k in sorted(params)) return s + query_str def sign_str(key, s, method): hmac_str = hmac.new(key.encode("utf8"), s.encode("utf8"), method).digest() return base64.b64encode(hmac_str) if __name__ == '__main__': endpoint = "cvm.tencentcloudapi.com" data = { 'Action' : 'DescribeInstances', 'InstanceIds.0' : 'ins-09dx96dg', 'Limit' : 20, 'Nonce' : 11886, 'Offset' : 0, 'Region' : 'ap-guangzhou', 'SecretId' : secret_id, 'Timestamp' : 1465185768, # int(time.time()) 'Version': '2017-03-12' } s = get_string_to_sign("GET", endpoint, data) data["Signature"] = sign_str(secret_key, s, hashlib.sha1) print(data["Signature"]) # 此处会实际调用,成功后可能产生计费 # resp = requests.get("https://" + endpoint, params=data) # print(resp.url) ``` ### Response #### Success Response (200) Prints the generated signature. The commented-out section shows how to make the actual API request. #### Response Example ``` zmmjn35mikh6pM3V7sUEuX4wyYM= ``` ``` -------------------------------- ### Java Signature Generation Source: https://tengxunfanyi.apifox.cn/doc-1404838 This section provides a Java code example demonstrating how to generate a signature for Tencent Cloud API 3.0 requests. It covers the steps for creating the string to sign, performing the HMAC-SHA1 signing, and constructing the final URL. ```APIDOC ## GET cvm.tencentcloudapi.com ### Description This example demonstrates how to construct and sign a request to the `DescribeInstances` API of the CVM product using Java. It includes the necessary steps for parameter sorting, HMAC-SHA1 signature generation, and URL encoding. ### Method GET ### Endpoint `https://cvm.tencentcloudapi.com/ ### Parameters #### Path Parameters None #### Query Parameters - **Action** (string) - Required - The name of the API action to perform (e.g., `DescribeInstances`). - **InstanceIds.0** (string) - Required - The ID of the instance to describe. - **Limit** (integer) - Optional - The maximum number of instances to return. - **Nonce** (integer) - Required - A random nonce value. - **Offset** (integer) - Optional - The starting offset for paginating results. - **Region** (string) - Required - The region to which the request is made. - **SecretId** (string) - Required - Your Tencent Cloud API access key ID. - **Timestamp** (integer) - Required - The Unix timestamp for the request. - **Version** (string) - Required - The API version to use (e.g., `2017-03-12`). - **Signature** (string) - Required - The generated signature for the request. ### Request Example ```java // Java code snippet for signature generation as provided in the input. import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Random; import java.util.TreeMap; import javax.crypto.Mac; import javax.crypto.spec.SecretKeySpec; import javax.xml.bind.DatatypeConverter; public class TencentCloudAPIDemo { private final static String CHARSET = "UTF-8"; public static String sign(String s, String key, String method) throws Exception { Mac mac = Mac.getInstance(method); SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(CHARSET), mac.getAlgorithm()); mac.init(secretKeySpec); byte[] hash = mac.doFinal(s.getBytes(CHARSET)); return DatatypeConverter.printBase64Binary(hash); } public static String getStringToSign(TreeMap params) { StringBuilder s2s = new StringBuilder("GETcvm.tencentcloudapi.com/?"); // 签名时要求对参数进行字典排序,此处用TreeMap保证顺序 for (String k : params.keySet()) { s2s.append(k).append("=").append(params.get(k).toString()).append("&"); } return s2s.toString().substring(0, s2s.length() - 1); } public static String getUrl(TreeMap params) throws UnsupportedEncodingException { StringBuilder url = new StringBuilder("https://cvm.tencentcloudapi.com/?"); // 实际请求的url中对参数顺序没有要求 for (String k : params.keySet()) { // 需要对请求串进行urlencode,由于key都是英文字母,故此处仅对其value进行urlencode url.append(k).append("=").append(URLEncoder.encode(params.get(k).toString(), CHARSET)).append("&"); } return url.toString().substring(0, url.length() - 1); } public static void main(String[] args) throws Exception { TreeMap params = new TreeMap(); // TreeMap可以自动排序 // 实际调用时应当使用随机数,例如:params.put("Nonce", new Random().nextInt(java.lang.Integer.MAX_VALUE)); params.put("Nonce", 11886); // 公共参数 // 实际调用时应当使用系统当前时间,例如: params.put("Timestamp", System.currentTimeMillis() / 1000); params.put("Timestamp", 1465185768); // 公共参数 params.put("SecretId", "AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******"); // 公共参数 params.put("Action", "DescribeInstances"); // 公共参数 params.put("Version", "2017-03-12"); // 公共参数 params.put("Region", "ap-guangzhou"); // 公共参数 params.put("Limit", 20); // 业务参数 params.put("Offset", 0); // 业务参数 params.put("InstanceIds.0", "ins-09dx96dg"); // 业务参数 params.put("Signature", sign(getStringToSign(params), "Gu5t9xGARNpq86cd98joQYCN3*******", "HmacSHA1")); // 公共参数 System.out.println(getUrl(params)); } } ``` ### Response #### Success Response (200) Returns the URL with the signature appended. #### Response Example ``` https://cvm.tencentcloudapi.com/?Action=DescribeInstances&InstanceIds.0=ins-09dx96dg&Limit=20&Nonce=11886&Offset=0&Region=ap-guangzhou&SecretId=AKIDz8krbsJ5yKBZQpn74WFkmLPx3*******&Signature=zmmjn35mikh6pM3V7sUEuX4wyYM%3D&Timestamp=1465185768&Version=2017-03-12 ``` ``` -------------------------------- ### 图片翻译 Source: https://tengxunfanyi.apifox.cn/doc-1404999 支持对图片中的文本进行识别和翻译。 ```APIDOC ## POST /api/translate/image ### Description Recognizes and translates text found within an image. ### Method POST ### Endpoint /api/translate/image ### Parameters #### Request Body - **imageContent** (string) - Required - Base64 encoded image content. - **source** (string) - Optional - The source language code of the text in the image. If not provided, auto-detection is used. - **target** (string) - Required - The target language code for the translation. ### Request Example ```json { "imageContent": "base64_encoded_image_data...", "source": "en", "target": "zh" } ``` ### Response #### Success Response (200) - **translatedText** (string) - The translated text extracted from the image. - **detectedSourceLanguage** (string) - The detected source language code if 'source' was not provided. #### Response Example ```json { "translatedText": "欢迎使用腾讯翻译!", "detectedSourceLanguage": "zh" } ``` ``` -------------------------------- ### Tencent Translate API Overview Source: https://tengxunfanyi.apifox.cn/doc-1404388 This section provides an overview of the Tencent Translate API, including its introductory documentation, data structures, and error codes. ```APIDOC ## Introduction to Tencent Translate API ### Description Provides an overview of the Tencent Translate API, its features, and how to get started. ## Data Structures ### Description Details the data structures used within the Tencent Translate API for requests and responses. ## Error Codes ### Description Lists and explains the error codes returned by the Tencent Translate API for troubleshooting. ``` -------------------------------- ### Tengxunfanyi API Success Response Example (JSON) Source: https://tengxunfanyi.apifox.cn/api-39724967 This snippet shows a successful response (HTTP 200) from the Tengxunfanyi API when generating code. It includes fields like SessionUuid, RecognizeStatus, SourceText, TargetText, Seq, Source, Target, and RequestId. The RecognizeStatus indicates the completion of voice recognition. ```json { "Response": { "RecognizeStatus": 0, "RequestId": "6e698139-615a-4d42-8dea-6bfada24e83c", "Seq": 0, "SessionUuid": "sid-1516105689129", "Source": "zh", "SourceText": "你好。", "Target": "en", "TargetText": "Hello." } } ``` -------------------------------- ### Signature Demo Recommendation Source: https://tengxunfanyi.apifox.cn/doc-1404536 For actual API 3.0 calls, it is recommended to use the accompanying Tencent Cloud SDK 3.0, which encapsulates the signature generation process. ```APIDOC ## Signature Demo When calling API 3.0 in practice, it is recommended to use the Tencent Cloud SDK 3.0. The SDK encapsulates the signature process, allowing developers to focus solely on the specific API interfaces provided by the product. For detailed information, please refer to the SDK Center. Currently supported programming languages include: - Python - Java - PHP - Go - NodeJS - .NET - C++ Signature demos for different products are available. You can find the corresponding product to reference signature generation. To clarify the signature process further, the following examples illustrate the signature generation steps with actual programming languages. The domain names, API calls, and parameter values used in these examples are based on the signature process described above. The code is intended for explanation purposes and may not be universally applicable. It is best to use the SDK for actual development. ``` -------------------------------- ### Translate Text using cURL Source: https://tengxunfanyi.apifox.cn/api-39731964 This example shows how to send a POST request to the Tencent Cloud Translate API using cURL to translate text from English to Chinese. It includes necessary headers like action, region, timestamp, version, authorization, token, language, and content type, along with the request body containing source text, source language, target language, and project ID. ```shell curl --location --request POST 'https://tmt.tencentcloudapi.com' \ --header 'X-TC-Action: TextTranslate' \ --header 'X-TC-Region;' \ --header 'X-TC-Timestamp;' \ --header 'X-TC-Version;' \ --header 'Authorization;' \ --header 'X-TC-Token;' \ --header 'X-TC-Language: zh-CN' \ --header 'Content-Type: application/json' \ --data-raw '{ "SourceText": "hello", "Source": "en", "Target": "zh", "ProjectId": 0 }' ``` -------------------------------- ### 语种识别 Source: https://tengxunfanyi.apifox.cn/doc-1404999 用于自动识别文本的语言。 ```APIDOC ## POST /api/translate/detect-language ### Description Automatically detects the language of the provided text. ### Method POST ### Endpoint /api/translate/detect-language ### Parameters #### Request Body - **text** (string) - Required - The text content to detect the language from. ### Request Example ```json { "text": "Hello, how are you?" } ``` ### Response #### Success Response (200) - **language** (string) - The detected language code (e.g., 'en', 'fr'). - **confidence** (number) - The confidence score of the detection. #### Response Example ```json { "language": "en", "confidence": 0.98 } ``` ``` -------------------------------- ### 文件翻译结果查询 Source: https://tengxunfanyi.apifox.cn/doc-1404999 用于查询已提交文件的翻译结果。 ```APIDOC ## GET /api/translate/file/query/{taskId} ### Description Retrieves the translation results for a previously submitted file task. ### Method GET ### Endpoint /api/translate/file/query/{taskId} ### Parameters #### Path Parameters - **taskId** (string) - Required - The task ID obtained from the file translation request. ### Response #### Success Response (200) - **status** (string) - The status of the translation task (e.g., 'processing', 'completed', 'failed'). - **translatedContent** (string) - The translated content of the file if the status is 'completed'. #### Response Example ```json { "status": "completed", "translatedContent": "翻译完成的内容..." } ``` ``` -------------------------------- ### 文件翻译请求 Source: https://tengxunfanyi.apifox.cn/doc-1404999 用于提交需要翻译的文件。 ```APIDOC ## POST /api/translate/file/request ### Description Submits a file for translation processing. ### Method POST ### Endpoint /api/translate/file/request ### Parameters #### Request Body - **fileContent** (string) - Required - Base64 encoded content of the file to be translated. - **fileName** (string) - Required - The name of the file. - **source** (string) - Optional - The source language code. - **target** (string) - Required - The target language code. ### Request Example ```json { "fileContent": "base64_encoded_file_data...", "fileName": "document.txt", "source": "en", "target": "zh" } ``` ### Response #### Success Response (200) - **taskId** (string) - A unique identifier for the file translation task. #### Response Example ```json { "taskId": "task_12345abcde" } ``` ``` -------------------------------- ### 腾讯翻译 API 语种识别请求 (Java) Source: https://tengxunfanyi.apifox.cn/api-39786791 使用 Java 调用腾讯翻译 API 进行语种识别。展示了如何构建请求和处理响应。 ```Java // 示例代码需要根据实际的 API 调用库进行适配,例如使用 Apache HttpClient 或 OkHttp // import org.apache.http.client.methods.HttpPost; // import org.apache.http.entity.StringEntity; // import org.apache.http.impl.client.CloseableHttpClient; // import org.apache.http.impl.client.HttpClients; // import org.apache.http.util.EntityUtils; // // public class TencentTranslate { // // public static void main(String[] args) { // try { // CloseableHttpClient httpClient = HttpClients.createDefault(); // HttpPost request = new HttpPost("https://tmt.tencentcloudapi.com"); // // request.setHeader("X-TC-Action", "LanguageDetect"); // request.setHeader("X-TC-Region", ""); // 根据需要填写 // request.setHeader("X-TC-Timestamp", String.valueOf(System.currentTimeMillis() / 1000)); // request.setHeader("X-TC-Version", "2018-03-21"); // request.setHeader("Authorization", ""); // 填写签名 // request.setHeader("X-TC-Language", "zh-CN"); // request.setHeader("Content-Type", "application/json"); // // String requestBody = "{\"Text\": \"hello\", \"ProjectId\": 0}"; // request.setEntity(new StringEntity(requestBody)); // // CloseableHttpResponse response = httpClient.execute(request); // String responseBody = EntityUtils.toString(response.getEntity()); // System.out.println(responseBody); // // httpClient.close(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } ``` -------------------------------- ### Construct String to Sign Source: https://tengxunfanyi.apifox.cn/doc-1404536 This snippet shows the format for concatenating components to create the string that will be signed. It includes the algorithm, timestamp, credential scope, and a hash of the canonical request. ```pseudocode StringToSign = Algorithm + \n + RequestTimestamp + \n + CredentialScope + \n + HashedCanonicalRequest ```