2025-02-28 09:42

Java访问DeepSeek-API

码自答

Java后端

(190)

(0)

收藏

一    注册DeepSeek用户,创建API-Key

        image.png


二    添加httpclient依赖

        image.png

<dependencies>
    <!-- Apache HttpClient -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.13</version> 
    </dependency>
</dependencies>


三    Java代码

package com.wanmait.demo;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
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;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class Main {
    public static void main(String[] args) {
        String url = "https://api.deepseek.com/chat/completions";
        String ak = "sk-*************************"; // 替换为你的 API Key
        
        CloseableHttpClient client = HttpClients.createDefault();
        
        // 创建 HTTP POST 请求
        HttpPost request = new HttpPost(url);
        //添加请求头
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Authorization", "Bearer " + ak);
        
        String content = "请问万码学堂在哪儿?";
        
        // 动态构建请求体
        String requestBody = String.format(
        "{\"model\": \"deepseek-chat\", \"messages\": [{\"role\": \"user\", \"content\": \"%s\"}], \"stream\": false}",
        content
        );
        
        try {
            request.setEntity(new StringEntity(requestBody));
            
            //发送请求
            CloseableHttpResponse response = client.execute(request);
            
            //接收响应
            String recive = EntityUtils.toString(response.getEntity());
            
            System.out.println(recive);
        } 
        catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } 
        catch (ClientProtocolException e) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}


0条评论

点击登录参与评论