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());

    }


}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值