Java对接百度文心一言,Java发送POST请求,类似前端AJAX

Java对接百度文心一言,Java发送POST请求,类似前端AJAX

    正在检查是否收录...

这是项目中使用的对接百度文心一言后端代码

public class BaiduChatApi { private static String CHAT_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant"; static String inp = "{\"messages\": [\n" + " {\n" + " \"role\": \"%s\",\n" + " \"content\": \"%s\"\n" + " }\n" + " ]}"; public static String getAnswerBaiDu(String text) throws IOException{ CHAT_URL = CHAT_URL+"?access_token=xxxx"; URL u=new URL(CHAT_URL); HttpURLConnection conn=(HttpURLConnection) u.openConnection(); conn.setConnectTimeout(10*1000); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "application/json"); OutputStream out= conn.getOutputStream(); try{ String json=String.format(inp,"user",text); System.err.println(json); out.write(json.getBytes("UTF-8")); out.close(); out=null; InputStream in = conn.getInputStream(); if(conn.getResponseCode()==200){ //流转换为二进制数组,read()是转换方法 byte[] data = new byte[1024]; int len = 0; ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((len = in.read(data)) != -1){ bos.write(data,0,len); } bos.close(); in.close(); conn.disconnect(); return new String(bos.toByteArray(), "UTF-8"); } else in.close(); }catch(Exception e){ e.printStackTrace(); } finally{ if(out!=null){ out.close(); } conn.disconnect(); } return null; } public static void main(String[] args) throws Exception { System.out.print("input>>"); String answer = getAnswerBaiDu("头疼怎么办"); System.err.println(answer); //使用ObjectMapper直接将String串转成对像 ObjectMapper objectMapper = new ObjectMapper(); BaiduChatModel chatModel = objectMapper.readValue(answer, BaiduChatModel.class); System.err.println(chatModel.toString()); System.err.println(chatModel.getResult()); } } 

chaturltpubaiduappstemjsoncodeapi百度文心ivatoken
  • 本文作者:李琛
  • 本文链接: https://wapzz.net/post-1463.html
  • 版权声明:本博客所有文章除特别声明外,均默认采用 CC BY-NC-SA 4.0 许可协议。
本站部分内容来源于网络转载,仅供学习交流使用。如涉及版权问题,请及时联系我们,我们将第一时间处理。
文章很赞!支持一下吧 还没有人为TA充电
为TA充电
还没有人为TA充电
0
  • 支付宝打赏
    支付宝扫一扫
  • 微信打赏
    微信扫一扫
感谢支持
文章很赞!支持一下吧
关于作者
2.3W+
5
0
1
WAP站长官方

美国空军部首席数据和AI官谈领先的AI运营和战略优势

上一篇

字节跳动利用AI对Linux内核进行优化 显著提高效率

下一篇
  • 复制图片
按住ctrl可打开默认菜单