当前位置:首页>文章>使用指南>Claude-Java示例代码

Claude-Java示例代码

文本是《工具配置(共30篇)》专题的第 29 篇。阅读本文前,建议先阅读前面的文章:

1. 资源准备

2. pom依赖

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.6</version>
</dependency>

3. 实现代码

import com.google.gson.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;

public class Java8AnthropicExample {
    /**
     * 这里填写在https://yibuapi.com网站上创建的API Key
     */
    private static final String API_KEY = "sk-xxxx";
    /**
     * 这里填写https://yibuapi.com/v1
     */
    private static final String BASE_URL = "https://yibuapi.com/v1";
    private static final String QUESTIONS = "生成三个虚构的中文书名及其作者和类型的清单。\n" +
            "使用以下键以 JSON 格式提供它们:book_id, title, author, genre.";

    public static void main(String[] args) {
        try {
            String response = getAnthropicResponse(QUESTIONS, API_KEY, BASE_URL);
            System.out.println("回答: " + response);
        } catch (Exception e) {
            System.out.println("请求失败: " + e.getMessage());
        }
    }

    private static String getAnthropicResponse(String question, String apiKey, String baseUrl) throws Exception {
        HttpURLConnection connection = null;
        try {
            // 创建连接
            URL url = new URL(baseUrl + "/messages");
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("x-api-key", apiKey);
            connection.setRequestProperty("anthropic-version", "2023-06-01");
            connection.setDoOutput(true);

            String requestBody = buildRequestBody(question);

            // 调试输出请求体(生产环境建议删除)
            System.out.println("请求体内容:\n" + requestBody);

            // 发送请求
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = requestBody.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 处理响应
            int statusCode = connection.getResponseCode();
            if (statusCode != 200) {
                // 获取错误响应详情
                String errorResponse = readErrorStream(connection);
                return "请求失败: HTTP " + statusCode + "\n错误详情: " + errorResponse;
            }

            try (BufferedReader br = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                StringBuilder response = new StringBuilder();
                String responseLine;
                while ((responseLine = br.readLine()) != null) {
                    response.append(responseLine);
                }
                return parseResponse(response.toString());
            }
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    private static String buildRequestBody(String question) {
        JsonObject message = new JsonObject();
        message.addProperty("role", "user");
        message.addProperty("content", question); // 直接使用字符串内容

        JsonArray messages = new JsonArray();
        messages.add(message);

        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("model", "claude-3-7-sonnet-latest");
        requestBody.addProperty("max_tokens", 1024);
        requestBody.add("messages", messages);

        return requestBody.toString();
    }

    private static String parseResponse(String jsonResponse) throws Exception {
        try {
            JsonObject obj = new JsonParser().parse(jsonResponse).getAsJsonObject();
            JsonArray content = obj.getAsJsonArray("content");
            if (content.size() == 0) {
                throw new Exception("响应内容为空");
            }
            JsonObject firstContent = content.get(0).getAsJsonObject();
            return firstContent.get("text").getAsString();
        } catch (JsonSyntaxException e) {
            throw new Exception("JSON解析失败: " + e.getMessage());
        }
    }

    // 新增错误流读取方法
    private static String readErrorStream(HttpURLConnection connection) {
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(connection.getErrorStream(), StandardCharsets.UTF_8))) {
            StringBuilder response = new StringBuilder();
            String responseLine;
            while ((responseLine = br.readLine()) != null) {
                response.append(responseLine);
            }
            return response.toString();
        } catch (Exception e) {
            return "无法读取错误信息: " + e.getMessage();
        }
    }
}

4. 运行效果

Claude-Java示例代码

您已阅读完《工具配置(共30篇)》专题的第 29 篇。请继续阅读该专题下面的文章:

使用指南

OpenAI-Java示例代码

2025-9-28 20:02:26

使用指南

whisper-1-Python示例代码

2025-9-30 11:05:29

搜索