实习时遇到一个需求,里面需要调用大模型的api,原先使用的是
import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost;
代码如下
public String quary(String question) {
String address = "";
String chatId = "";
String apiKey = "";
String responseString = null;
String responseStr = null;
String session_id = null;
String url = "http://" + address + "/api/v1/chats/" + chatId + "/completions";
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
// 设置请求头
post.setHeader("Content-Type", "application/json");
post.setHeader("Authorization", "Bearer " + apiKey);
// 设置请求体
String json = "{\"question\": \"hello\"}";
StringEntity entity = null;
try {
entity = new StringEntity(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
post.setEntity(entity);
try {
HttpResponse res = client.execute(post);
responseStr = EntityUtils.toString(res.getEntity(), "UTF-8");
} catch (IOException e) {
e.printStackTrace();
}
但执行之后发现:调用大模型所传的问题乱码,想了很多招也无法解决,最后在导师的建议下使用了hutool包
1、导入依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
</dependency>
2、编写代码
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
public String quary(String question) {
String address = "";
String Apikey="";
String url = "http://" + address + "/api/v1/chat/completions";
// 构建请求体
JSONObject json = new JSONObject();
//json.put("chatId", "my_chatId");
json.put("stream", false);
json.put("detail", false);
json.put("responseChatItemId", "my_responseChatItemId");
JSONObject variables = new JSONObject();
variables.put("uid", "asdfadsfasfd2323");
variables.put("name", "张三");
json.put("variables", variables);
JSONObject message = new JSONObject();
message.put("role", "user");
message.put("content", question);
JSONObject[] messagesArray = {message};
json.put("messages", messagesArray);
// 发送 POST 请求
HttpResponse res = (HttpResponse) HttpRequest.post(url)
.header("Authorization", "Bearer " + Apikey)
.header("Content-Type", "application/json")
.body(json.toString())
.execute();
// 获取响应字符串
String responseStr = res.body();
JSONObject jsonObject = JSONUtil.parseObj(responseStr);
JSONArray choicesArray = jsonObject.getJSONArray("choices");
// 获取数组中的第一个元素(JSONObject)
JSONObject firstChoiceObject = choicesArray.getJSONObject(0);
// 获取 message 对象
JSONObject messageObject = firstChoiceObject.getJSONObject("message");
// 提取 content 字段
String content = messageObject.getStr("content");
return content;
}