用【Java】调用百度千帆大模型并提供流式接口【SSE】响应
import okhttp3.*;
import java.io.IOException;
public class BaiduSSEClient {
private static final String API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/classification/self/service";
private static final String ACCESS_TOKEN = "你的access_token";
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(API_URL)
.header("Authorization", "Bearer " + ACCESS_TOKEN)
.header("Content-Type", "application/json")
.method("GET", null)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// 处理服务端发送的事件流(SSE)
try (ResponseBody responseBody = response.body()) {
BufferedSource source = responseBody.source();
while (!source.exhausted()) {
String line = source.readUtf8Line();
// 解析并处理每一行数据
System.out.println(line);
}
}
}
});
}
}
这段代码使用了OkHttp库来发起对百度千帆大模型的SSE请求。在请求头中添加了认证信息,并且指定了处理服务端发送的事件流。在响应处理方法中,我们读取并打印了每一行数据。这个例子展示了如何使用Java代码与百度AI平台上的千帆大模型进行交互。
评论已关闭