1. 安装Ollama Search

2. 调用

相关依赖

    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.14</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.17.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.12</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>2.0.12</version>
        </dependency>
    </dependencies>

客户端

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
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 java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 程慧聪
 * @date 2025/8/22-16:19
 */
public class OllamaClient {
	private static final String OLLAMA_API_URL = "http://localhost:11434/api/generate";

	public static void main(String[] args) {
		try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
			HttpPost postRequest = new HttpPost(OLLAMA_API_URL);
			postRequest.setHeader("Content-Type", "application/json; charset=UTF-8");

			Map<String, Object> requestBody = new HashMap<>();
			requestBody.put("model", "qwen3:0.6b");
			requestBody.put("system", "你是一个编程高手");
			requestBody.put("prompt", "请问C语言和C++的区别是什么?");
			requestBody.put("stream", false);

			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString(requestBody);
			postRequest.setEntity(new StringEntity(json, StandardCharsets.UTF_8));

			try (CloseableHttpResponse response = httpClient.execute(postRequest);
			     BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))) {

				StringBuilder resultBuilder = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					if (!line.trim().isEmpty()) {
						JsonNode jsonNode = objectMapper.readTree(line);
						if (jsonNode.has("response")) {
							resultBuilder.append(jsonNode.get("response").asText());
						}
						if (jsonNode.has("done") && jsonNode.get("done").asBoolean()) {
							break;
						}
					}
				}
				System.out.println("Ollama: " + resultBuilder);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

更多推荐