// Auto-generated Java API extension
import java.util.*;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import com.fasterxml.jackson.databind.ObjectMapper;
public class {{target}} {
// 可以定义基础属性或方法
protected String baseUrl = "";
protected HttpClient httpClient = HttpClient.newHttpClient();
protected ObjectMapper objectMapper = new ObjectMapper();
}
public class {{target}}Ext extends {{target}} {
{{#each endpoints}}
/**
* {{#if this.description}}{{this.description}}{{else}}{{this.name}}{{/if}}
*/
public {{this.response_type}} {{this.name}}(
{{#each this.params}}{{this.ty}} {{this.name}}, {{/each}}
{{#if this.body_param}}{{this.body_param.ty}} form, {{/if}}
) throws Exception {
{{#if this.params}}
String url = this.baseUrl + "{{this.path}}"{{#each this.params}}{{#if (eq this.location "path")}}.replace("{{this.name}}", String.valueOf({{this.name}})){{/if}}{{/each}};
{{else}}
String url = this.baseUrl + "{{this.path}}";
{{/if}}
{{#if this.query_params.length}}
StringBuilder queryBuilder = new StringBuilder();
{{#each this.query_params}}
if ({{this.name}} != null) {
if (queryBuilder.length() > 0) queryBuilder.append("&");
queryBuilder.append("{{this.name}}=").append(URLEncoder.encode(String.valueOf({{this.name}}), StandardCharsets.UTF_8));
}
{{/each}}
if (queryBuilder.length() > 0) {
url += "?" + queryBuilder.toString();
}
{{/if}}
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.uri(URI.create(url))
.header("Content-Type", "application/json");
{{#if this.body_param}}
if (form != null) {
String jsonBody = objectMapper.writeValueAsString(form);
requestBuilder.{{this.method}}("{{this.method}}", HttpRequest.BodyPublishers.ofString(jsonBody));
} else {
requestBuilder.{{this.method}}("{{this.method}}", HttpRequest.BodyPublishers.noBody());
}
{{else}}
requestBuilder.{{this.method}}("{{this.method}}", HttpRequest.BodyPublishers.noBody());
{{/if}}
HttpRequest request = requestBuilder.build();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() >= 400) {
throw new RuntimeException("HTTP error: " + response.statusCode());
}
{{#if (eq this.response_type "String")}}
return response.body();
{{else}}
return objectMapper.readValue(response.body(), {{this.response_type}}.class);
{{/if}}
}
{{/each}}
}