当前位置:   article > 正文

1,java如何调用AI——百度智能云千帆大模型_java ai

java ai

首先要去官方百度智能大模型申请网上有教程在这里就不展示了,申请成功后,在Java中引入依赖:

  1. <dependency>
  2. <groupId>com.squareup.okhttp3</groupId>
  3. <artifactId>okhttp</artifactId>
  4. <version>4.9.0</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>fastjson</artifactId>
  9. <version>1.2.28</version>
  10. </dependency>

版本号选择自己合适的,接下来就将下面的代码写进自己的类中即可:

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

调用测试一下 :

  1. package utils;
  2. import java.io.IOException;
  3. public class MainClass {
  4. public static void main(String[] args) throws IOException {
  5. try {
  6. GPT GPT = new GPT();
  7. GPT.main(args);
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. }
  12. }

 

 

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

闽ICP备14008679号