import lombok.extern.slf4j.Slf4j; import okhttp3.*; import okio.BufferedSource; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import java.io.IOException; import java.util.concurrent.TimeUnit; @Slf4j public class TestRot { public static void testRobotRwq() { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .build(); /* JSONObject params = new JSONObject(); params.put("question", question);*/ String requestStr = "{\n" + " \"id\": \"683a65fd-8feb-4446-ad32-714c4785f667\",\n" + " \"enterprise_id\": \"orion.ovs.entprise.6687895631\",\n" + " \"device_id\": \"M03SCN00030230362FFA\",\n" + " \"messages\": [\n" + " {\n" + " \"role\": \"user\",\n" + " \"content\": \"今天天气怎么样?\"\n" + " }\n" + " ],\n" + " \"max_tokens\": 2048,\n" + " \"stream\": true\n" + "}"; RequestBody requestBody = RequestBody.create(requestStr, MediaType.parse("application/json; charset=utf-8")); // 封装请求头 Headers headers = new Headers.Builder() .set("Content-Type", "application/json") .set("Accept", "text/event-stream") .build(); Request request = new Request.Builder() .url("http://localhost:18006/chat/base") //.url("http://robot.scsmile.cn/chat/base") .headers(headers) .post(requestBody) .build(); Call call = client.newCall(request); // 4. 监听回调 call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { log.error("进入 onFailure方法 {}", e.getMessage(), e); // sseEmitter.completeWithError(e); } @Override public void onResponse(Call call, Response response) throws IOException { if (response.isSuccessful()) { String chunkMessage = ""; BufferedSource source = response.body().source(); while (!source.exhausted()) { chunkMessage = source.readUtf8Line(); if (StringUtils.isBlank(chunkMessage)) { continue; } /* JSONObject jsonObject = JSONObject.parseObject(chunkMessage); if (null != jsonObject && null != jsonObject.getJSONObject("data")) { String answer = jsonObject.getJSONObject("data").getString("answer"); // sseEmitter.send(answer); }*/ log.info("chunkMessage:{}", chunkMessage); } } else { // log.error("onResponse 方法请求失败 {}", response.message()); // TODO 重新发起请求 } } }); } public static void main(String[] args) { testRobotRwq(); } }