示例:JAVA调用deepseek

 近日,国产AI DeepSeek在中国、美国的科技圈受到广泛关注,甚至被认为是大模型行业的最大“黑马”。在外网,DeepSeek被不少人称为“神秘的东方力量”。1月27日,DeepSeek应用登顶苹果美国地区应用商店免费APP下载排行榜,在美区下载榜上超越了ChatGPT。同日,苹果中国区应用商店免费榜显示,DeepSeek成为中国区第一。总之就是deepseek目前比较火,同时也提供了开放平台,尝试接入一下,也比较方便,官网每个接口都提供了各种语言的示例代码,java采用的okhttp,我用httpurlconnection尝试下

一、获取 API key

开放平台地址:DeepSeek

登录deepseek开放平台,创建API keys,注意创建的时候复制key,要不然找不到了

新账号有10元的体验额度,不足可以充值,10元体验额度的有效期为1个月

v3和R1的收费标准

1. deepseek-chat 模型优惠期至北京时间 2025 年 2 月 8 日 24:00,期间 API 调用享历史价格,优惠结束后将按每百万输入 tokens 2 元,每百万输出 tokens 8 元计费
2. deepseek-reasoner 模型上线即按每百万输入 tokens 4 元,每百万输出 tokens 16 元计费

二、获取开放API文档

接口地址:首次调用 API | DeepSeek API Docs

进入接口文档,提供了对话、补全、模型等接口,我们找一个【对话补全】接口,给了一个上下文,让他补充说话

三、JAVA调用API文档

使用java调用API,跟其他接口没什么区别,方便上手,注意下入参和返回参数就可以,采用json格式。

-----对话上下文

 { "content": "欢迎加入虚拟电厂", "role": "system" , "name": "muyunfei" },

 { "content": "你好,虚拟电厂与deepseek结合的方向说一下吧", "role": "user" , "name": "路人甲"}

组装请求参数:

{
	"messages": [{
		"content": "欢迎加入虚拟电厂",
		"role": "system",
		"name": "muyunfei"
	}, {
		"content": "你好,虚拟电厂与deepseek结合的方向说一下吧",
		"role": "user",
		"name": "路人甲"
	}],
	"model": "deepseek-chat",
	"frequency_penalty": 0,
	"max_tokens": 2048,
	"presence_penalty": 0,
	"response_format": {
		"type": "text"
	},
	"stop": null,
	"stream": false,
	"stream_options": null,
	"temperature": 1,
	"top_p": 1,
	"tools": null,
	"tool_choice": "none",
	"logprobs": false,
	"top_logprobs": null
}

返回数据参数格式:

{
			"id": "2fe86f3b-6e3b-4e65-b35a-1127c14c8739",
			"object": "chat.completion",
			"created": 1738810567,
			"model": "deepseek-chat",
			"choices": [{
				"index": 0,
				"message": {
					"role": "assistant",
					"content": "Hello! How can I assist you today? 😊"
				},
				"logprobs": null,
				"finish_reason": "stop"
			}],
			"usage": {
				"prompt_tokens": 9,
				"completion_tokens": 11,
				"total_tokens": 20,
				"prompt_tokens_details": {
					"cached_tokens": 0
				},
				"prompt_cache_hit_tokens": 0,
				"prompt_cache_miss_tokens": 9
			},
			"system_fingerprint": "fp_3a5770e1b4"
		}

------------------------------------------------------------------------

--------------------------      完整代码      ------------------------



import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


/**
 * 实现了。。。。。。
 *
 * @author 牟云飞
 *
 *<p>Modification History:</p>
 *<p>Date					Author			Description</p>
 *<p>------------------------------------------------------------------</p>
 *<p>2025年2月4日			牟云飞			新建</p>
 */
public class DeepseekTestMain {

	private static final String DEEPSEEK_API_URL_COMPLETIONS = "https://api.deepseek.com/chat/completions"; // API地址 ——
																											// 对话补全

	private static final String DEEPSEEK_API_KEY = "换成自己的key"; // 官网申请的api key


	public static void main(String[] args) {
		DeepseekTestMain test = new DeepseekTestMain();
		try {
			test.sendDeepseekChat(DEEPSEEK_API_URL_COMPLETIONS, "虚拟电厂与deepseek结合的方向说一下");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 对话补全
	 * 
	 * @param mess
	 * @return
	 * @throws IOException
	 */
	public String sendDeepseekChat(String deepseekUrl, String context) throws IOException {
		String result = null;

		URL url_req = new URL(deepseekUrl);

		HttpsURLConnection connection = (HttpsURLConnection) url_req.openConnection();

		// 设置参数
		connection.setDoOutput(true); // 需要输出
		connection.setDoInput(true); // 需要输入
		connection.setUseCaches(false); // 不允许缓存
		connection.setConnectTimeout(60000); // 设置连接超时
		connection.setReadTimeout(60000); // 设置读取超时
		connection.setRequestMethod("POST"); // 设置POST方式连接

		// 设置请求属性
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setRequestProperty("Accept", "application/json");
		connection.setRequestProperty("Charset", "UTF-8");

		// 设置请求头参数
		connection.addRequestProperty("Authorization", "Bearer " + DEEPSEEK_API_KEY); // 设置appId

		HttpsURLConnection https = (HttpsURLConnection) connection;
		SSLSocketFactory oldSocketFactory = trustAllHosts(https);
		HostnameVerifier oldHostnameVerifier = https.getHostnameVerifier();
		https.setHostnameVerifier(DO_NOT_VERIFY);



		// 输入数据
		String requestData = "{ \"messages\": "
							+ "[ "
				+ " { \"content\": \"欢迎加入虚拟电厂\", \"role\": \"system\" , \"name\": \"muyunfei\" }, "
				+ " { \"content\": \"你好,虚拟电厂与deepseek结合的方向说一下吧\", \"role\": \"user\" , \"name\": \"路人甲\"} "
				            + "],"
				       + " \"model\": \"deepseek-chat\","
				       + " \"frequency_penalty\": 0,"
				       + " \"max_tokens\": 2048,"
				       + " \"presence_penalty\": 0,"
				       + " \"response_format\": {\n \"type\": \"text\"\n },"
				       + " \"stop\": null,"
				       + " \"stream\": false,"
				       + " \"stream_options\": null,"
				       + " \"temperature\": 1,"
				       + " \"top_p\": 1,"
				       + " \"tools\": null,"
				       + " \"tool_choice\": \"none\","
				       + " \"logprobs\": false,"
				+ " \"top_logprobs\": null}";
		try (OutputStream os = connection.getOutputStream()) {
			byte[] input = requestData.getBytes("utf-8");
			os.write(input,0,input.length);
		}
		
		// 输出数据
		InputStream in = connection.getInputStream(); // 获取返回数据
		BufferedInputStream bis = new BufferedInputStream(in);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int c;
		while (-1 != (c = bis.read())) {
			baos.write(c);
		}
		bis.close();
		in.close();
		baos.flush();

		byte[] data = baos.toByteArray();
		String responseMsg = new String(data);
		System.out.println(responseMsg);
//		{
//			"id": "2fe86f3b-6e3b-4e65-b35a-1127c14c8739",
//			"object": "chat.completion",
//			"created": 1738810567,
//			"model": "deepseek-chat",
//			"choices": [{
//				"index": 0,
//				"message": {
//					"role": "assistant",
//					"content": "Hello! How can I assist you today? 😊"
//				},
//				"logprobs": null,
//				"finish_reason": "stop"
//			}],
//			"usage": {
//				"prompt_tokens": 9,
//				"completion_tokens": 11,
//				"total_tokens": 20,
//				"prompt_tokens_details": {
//					"cached_tokens": 0
//				},
//				"prompt_cache_hit_tokens": 0,
//				"prompt_cache_miss_tokens": 9
//			},
//			"system_fingerprint": "fp_3a5770e1b4"
//		}
		JSONObject jsonObject = JSONObject.fromObject(responseMsg);
		JSONArray choices = JSONArray.fromObject(jsonObject.get("choices"));// 获取补全内容,是个数组,多个补全回复多个
		System.out.println(choices.toString());
		JSONObject item = JSONObject.fromObject(JSONObject.fromObject(choices.get(0)).get("message"));
		System.out.println(item.get("content"));
		// 对JSON作解析

		return result;
	}

	private SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
		SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			SSLSocketFactory newFactory = sc.getSocketFactory();
			connection.setSSLSocketFactory(newFactory);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return oldFactory;
	}

	private TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return new java.security.cert.X509Certificate[] {};
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}
	} };

	private HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	};

}

### Java调用DeepSeek API示例 为了在Java项目中成功调用DeepSeek API,需先完成API Key的创建并配置好开发环境。假设当前使用的JDK版本为1.8。 #### 导入依赖库 确保项目的`pom.xml`文件中包含了必要的HTTP客户端库,例如Apache HttpClient: ```xml <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.13</version> </dependency> ``` #### 编写请求方法 下面是一个简单的GET请求例子来获取数据[^1]: ```java import org.apache.http.HttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class DeepSeekClient { private static final String API_KEY = "your_api_key_here"; public String fetchData(String endpoint) throws Exception { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet request = new HttpGet(endpoint); request.setHeader("Authorization", "Bearer " + API_KEY); HttpResponse response = httpClient.execute(request); return EntityUtils.toString(response.getEntity()); } } } ``` 此代码片段展示了如何通过设置授权头发送带有API密钥的身份验证信息给服务器,并接收返回的数据字符串形式的内容。 对于POST请求或其他类型的交互,则可以根据实际需求调整上述模板中的细节部分,比如改变HttpMethod类型以及添加更多的自定义头部或主体参数等。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牟云飞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值