java调用文心一言API的方法

打印 上一主题 下一主题

主题 543|帖子 543|积分 1629

话不多说,直接上干货:
一、首先去官网注册一个账号百度智能云-登录 (baidu.com),注册完成后等待审核,审核后就可以去控制台操纵啦!
二、根据官网介绍,由于文心一言属于收费产品(也有免费的,但功能限定),因此发起可以充值几块钱,足以做实验用了。我这里用的是“千帆大模型”产品。

三、代码实现过程:
 1)调用工具:
  1. package utils;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.JSONArray;
  4. import com.alibaba.fastjson.JSONObject;
  5. import okhttp3.*;
  6. import java.io.*;
  7. import java.net.URLEncoder;
  8. import java.util.ArrayList;
  9. import java.util.HashMap;
  10. public class ChineseGPT {
  11.     static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
  12.     public static void main(String []args) throws IOException{
  13.         //1、获取token
  14.         String access_token = new ChineseGPT().getWenxinToken();
  15.         //2、访问数据
  16.         String requestMethod = "POST";
  17.         String body = URLEncoder.encode("junshi","UTF-8");//设置要传的信息
  18.         String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token="+access_token;//post请求时格式
  19.         //测试:访问聚合数据的地区新闻api
  20.         HashMap<String, String> msg = new HashMap<>();
  21.         msg.put("role","user");
  22.         msg.put("content", "帮我写一篇关于介绍吉林市的小短文,大概100字左右");
  23.         ArrayList<HashMap> messages = new ArrayList<>();
  24.         messages.add(msg);
  25.         HashMap<String, Object> requestBody = new HashMap<>();
  26.         requestBody.put("messages", messages);
  27.         String outputStr = JSON.toJSONString(requestBody);
  28.         JSON json = HttpRequest.httpRequest(url,requestMethod,outputStr,"application/json");
  29.         System.out.println(json);
  30.     }
  31.     public String getWenxinToken() throws IOException {
  32.         MediaType mediaType = MediaType.parse("application/json");
  33.         RequestBody body = RequestBody.create(mediaType, "");
  34.         Request request = new Request.Builder()
  35.                 .url("https://aip.baidubce.com/oauth/2.0/token?client_id=xxxxxxxxxxxxxxxxxx&client_secret=xxxxxxxxxxxxxxxxxx&grant_type=client_credentials") //按官网要求填写你申请的key和相关秘钥
  36.                 .method("POST", body)
  37.                 .addHeader("Content-Type", "application/json")
  38.                 .addHeader("Accept", "application/json")
  39.                 .build();
  40.         Response response = HTTP_CLIENT.newCall(request).execute();
  41.         String s = response.body().string();
  42.         JSONObject objects = JSONArray.parseObject(s);
  43.         String msg = objects.getString("access_token");
  44.         System.out.println(msg);
  45.         return msg;
  46.     }
  47. }
复制代码
2)哀求工具:
  1. package utils;
  2. import com.alibaba.fastjson.JSONObject;
  3. import javax.net.ssl.HttpsURLConnection;
  4. import java.io.*;
  5. import java.net.ConnectException;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLConnection;
  9. import java.util.List;
  10. import java.util.Map;
  11. public class HttpRequest {
  12.    
  13.     /**
  14.      * post/GET远程请求接口并得到返回结果
  15.      *
  16.      * @param requestUrl 请求地址
  17.      * @param requestMethod 请求方法post/GET
  18.      * @return
  19.      */
  20.     public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr,String contentType) {
  21.         JSONObject jsonObject = null;
  22.         StringBuffer buffer = new StringBuffer();
  23.         try {
  24.             URL url = new URL(requestUrl);
  25.             HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();
  26.             httpUrlConn.setDoOutput(true);
  27.             httpUrlConn.setDoInput(true);
  28.             httpUrlConn.setUseCaches(false);
  29.             // 设置请求方式(GET/POST)
  30.             httpUrlConn.setRequestMethod(requestMethod);
  31.             //设置头信息
  32. //            httpUrlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
  33.             httpUrlConn.setRequestProperty("Content-Type",contentType);
  34.             httpUrlConn.setRequestProperty("Accept","application/json;charset=UTF-8");
  35.             // 设置连接主机服务器的超时时间:15000毫秒
  36.             httpUrlConn.setConnectTimeout(15000);
  37.             // 设置读取远程返回的数据时间:60000毫秒
  38.             httpUrlConn.setReadTimeout(60000);
  39.             if ("GET".equalsIgnoreCase(requestMethod)){
  40.                 httpUrlConn.connect();
  41.             }
  42.             // 当有数据需要提交时
  43.             if (null != outputStr) {
  44.                 OutputStream outputStream = httpUrlConn.getOutputStream();
  45.                 // 注意编码格式,防止中文乱码
  46.                 outputStream.write(outputStr.getBytes("UTF-8"));
  47.                 outputStream.close();
  48.             }
  49.             // 将返回的输入流转换成字符串
  50.             InputStream inputStream = httpUrlConn.getInputStream();
  51.             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
  52.             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  53.             String str = null;
  54.             while ((str = bufferedReader.readLine()) != null) {
  55.                 buffer.append(str);
  56.             }
  57.             bufferedReader.close();
  58.             inputStreamReader.close();
  59.             // 释放资源
  60.             inputStream.close();
  61.             inputStream = null;
  62.             httpUrlConn.disconnect();
  63.             jsonObject = JSONObject.parseObject(buffer.toString());
  64.         } catch (ConnectException ce) {
  65.         } catch (Exception e) {
  66.         }
  67.         return jsonObject;
  68.     }
  69. }
复制代码
3)执行main方法执行即可。

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

商道如狼道

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表