Java调用接口示例
- Java调用(原生)
GET请求
java
public static void main(String[] args) throws Exception {
// 认证参数
String appKey ="129faad0fa8a4e0e9bc27e45bbb68d49"; // key
String appSecret = "ef8f295ed7b342d886ace2e15e14c289"; // 密钥
long timeStamp = Instant.now().toEpochMilli(); // 时间戳毫秒级
// 1. 创建 HttpClient
HttpClient client = HttpClient.newHttpClient();
// 2. 构建带 Query 参数的 URL
String url = "https://demo.com/api/web/v1/user/list";
String query = "apiId=10000";
URI uri = URI.create(url + "?" + query); // 手动拼接 Query 参数
// 3. 加密
String data = appSecret + timeStamp; // 直接拼接待加密内容
String sign = SM3Util.hash(data);
// 4. 创建请求并添加 Headers
HttpRequest request = HttpRequest.newBuilder()
.uri(uri)
.GET()
.header("Content-Type", "application/json")
.header("appkey", appKey)
.header("timestamp", timeStamp+"")
.header("sign", sign)
.build();
// 5. 发送请求并获取响应
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString()
);
System.out.println("Response Body: " + response.body());
}POST请求
java
public static void main(String[] args) throws Exception {
// 认证参数
String appKey ="129faad0fa8a4e0e9bc27e45bbb68d49"; // key
String appSecret = "ef8f295ed7b342d886ace2e15e14c289"; // 密钥
long timeStamp = Instant.now().toEpochMilli(); // 时间戳毫秒级
// 1. 创建 HttpClient
HttpClient client = HttpClient.newHttpClient();
// 2. 构建 JSON 请求体
String jsonBody = "{}";
// 3. 加密
String data = appSecret + timeStamp; // 直接拼接待加密内容
String sign = SM3Util.hash(data);
// 4. 创建请求并添加 Headers
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://demo.com/api/web/v1/user"))
.POST(HttpRequest.BodyPublishers.ofString(jsonBody))
.header("Content-Type", "application/json")
.header("appkey", appKey)
.header("timestamp", timeStamp+"")
.header("sign", sign)
.build();
// 5. 发送请求并获取响应
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString()
);
System.out.println("Response Body: " + response.body());
}- Java调用(Okhttp)
java
OkHttpClient client = new OkHttpClient().newBuilder().build();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"id\": 1}");
Request request = new Request.Builder()
.url("http://127.0.0.1/api/web/user/list")
.method("POST",body)
.addHeader("appkey","你的应用appKey")
.addHeader("timestamp","时间戳")
.addHeader("sign","签名加密串")
.addHeader("Content-Type","")
.build();
Response response = client.newCall(request).execute();