当前位置:   article > 正文

java调用文心一言API的方法_java对接文心一言

java对接文心一言

话不多说,直接上干货:

一、首先去官网注册一个账号百度智能云-登录 (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. * post/GET远程请求接口并得到返回结果
  14. *
  15. * @param requestUrl 请求地址
  16. * @param requestMethod 请求方法post/GET
  17. * @return
  18. */
  19. public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr,String contentType) {
  20. JSONObject jsonObject = null;
  21. StringBuffer buffer = new StringBuffer();
  22. try {
  23. URL url = new URL(requestUrl);
  24. HttpURLConnection httpUrlConn = (HttpURLConnection)url.openConnection();
  25. httpUrlConn.setDoOutput(true);
  26. httpUrlConn.setDoInput(true);
  27. httpUrlConn.setUseCaches(false);
  28. // 设置请求方式(GET/POST)
  29. httpUrlConn.setRequestMethod(requestMethod);
  30. //设置头信息
  31. // httpUrlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
  32. httpUrlConn.setRequestProperty("Content-Type",contentType);
  33. httpUrlConn.setRequestProperty("Accept","application/json;charset=UTF-8");
  34. // 设置连接主机服务器的超时时间:15000毫秒
  35. httpUrlConn.setConnectTimeout(15000);
  36. // 设置读取远程返回的数据时间:60000毫秒
  37. httpUrlConn.setReadTimeout(60000);
  38. if ("GET".equalsIgnoreCase(requestMethod)){
  39. httpUrlConn.connect();
  40. }
  41. // 当有数据需要提交时
  42. if (null != outputStr) {
  43. OutputStream outputStream = httpUrlConn.getOutputStream();
  44. // 注意编码格式,防止中文乱码
  45. outputStream.write(outputStr.getBytes("UTF-8"));
  46. outputStream.close();
  47. }
  48. // 将返回的输入流转换成字符串
  49. InputStream inputStream = httpUrlConn.getInputStream();
  50. InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
  51. BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  52. String str = null;
  53. while ((str = bufferedReader.readLine()) != null) {
  54. buffer.append(str);
  55. }
  56. bufferedReader.close();
  57. inputStreamReader.close();
  58. // 释放资源
  59. inputStream.close();
  60. inputStream = null;
  61. httpUrlConn.disconnect();
  62. jsonObject = JSONObject.parseObject(buffer.toString());
  63. } catch (ConnectException ce) {
  64. } catch (Exception e) {
  65. }
  66. return jsonObject;
  67. }
  68. }

3)执行main方法执行即可。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/126535
推荐阅读
相关标签
  

闽ICP备14008679号