首次调用
http请求
curl https://api.deepseek.com/chat/completions \-H "Content-Type: application/json" \-H "Authorization: Bearer <DeepSeek API Key>" \-d '{"model": "deepseek-chat","messages": [{"role": "system", "content": "You are a helpful assistant."},{"role": "user", "content": "Hello!"}],"stream": false}'
{"role": "system", "content": "You are a helpful assistant."}
代码
@Testpublic void deepSeekApiOne() {// DeepSeek API KeyString apiKey = "sk-87553aba7e5b4554bfd773cd3056414d";// 创建 OkHttpClient 实例并设置超时时间OkHttpClient client = new OkHttpClient.Builder().connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS).readTimeout(READ_TIMEOUT, TimeUnit.SECONDS).writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS).build();String systemRoleContent = "You are a helpful assistant.";String userRoleContent = "介绍一下魔兽争霸";// 使用 Gson 构建请求体JsonObject requestBodyJson = new JsonObject();requestBodyJson.addProperty("model", "deepseek-chat");JsonArray messagesArray = new JsonArray();JsonObject systemMessage = new JsonObject();systemMessage.addProperty("role", "system");systemMessage.addProperty("content", systemRoleContent);messagesArray.add(systemMessage);JsonObject userMessage = new JsonObject();userMessage.addProperty("role", "user");userMessage.addProperty("content", userRoleContent);messagesArray.add(userMessage);requestBodyJson.add("messages", messagesArray);requestBodyJson.addProperty("stream", false);Gson gson = new Gson();String jsonBody = gson.toJson(requestBodyJson);MediaType JSON = MediaType.parse("application/json; charset=utf-8");RequestBody body = RequestBody.create(JSON, jsonBody);// 构建请求Request request = new Request.Builder().url("https://api.deepseek.com/chat/completions").post(body).addHeader("Content-Type", "application/json").addHeader("Authorization", "Bearer " + apiKey).build();int retryCount = 0;while (retryCount < MAX_RETRIES) {try (Response response = client.newCall(request).execute()) {if (response.isSuccessful()) {String responseBody = response.body().string();System.out.println("响应结果: " + responseBody);return;} else {System.out.println("请求失败,状态码: " + response.code());String errorBody = response.body() != null ? response.body().string() : "无错误响应内容";System.out.println("响应内容: " + errorBody);}} catch (IOException e) {System.out.println("请求因异常失败: " + e.getMessage());if (retryCount < MAX_RETRIES - 1) {System.out.println("正在重试请求... 第 " + (retryCount + 2) + " 次,共 " + MAX_RETRIES + " 次尝试");}}retryCount++;}System.out.println("已达到最大重试次数,请求失败。");}
}