• 调用okhttp3的案例代码


    1. <dependency>
    2. <groupId>com.squareup.okhttp3groupId>
    3. <artifactId>okhttpartifactId>
    4. <version>4.10.0version>
    5. dependency>
    1. package com.ftm.main.service.impl;
    2. import com.alibaba.fastjson2.JSONObject;
    3. import okhttp3.*;
    4. import org.springframework.stereotype.Service;
    5. @Service("SampleServiceImpl")
    6. public class SampleServiceImpl {
    7. public static final String API_KEY = "LWArx3rK8t5jaDWgYK0PAhUn";
    8. public static final String SECRET_KEY = "EHUudzDvELkgWXEGrDkRmcGKRE8qYkRx";
    9. static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
    10. /**
    11. * 从用户的AK,SK生成鉴权签名(Access Token)
    12. *
    13. * @return 鉴权签名(Access Token)
    14. * @throws Exception IO异常
    15. */
    16. public String getAccessToken() throws Exception {
    17. MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
    18. RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
    19. + "&client_secret=" + SECRET_KEY);
    20. Request request = new Request.Builder()
    21. .url("https://aip.baidubce.com/oauth/2.0/token")
    22. .method("POST", body)
    23. .addHeader("Content-Type", "application/x-www-form-urlencoded")
    24. .build();
    25. Response response = HTTP_CLIENT.newCall(request).execute();
    26. return JSONObject.parseObject(response.body().string()).getString("access_token");
    27. }
    28. public String getNewsSummary(String askTitle,String askContent) throws Exception{
    29. MediaType mediaType = MediaType.parse("application/json");
    30. JSONObject askJson = new JSONObject();
    31. askJson.put("max_summary_len", "200");
    32. askJson.put("title",askTitle);
    33. askJson.put("content",askContent);
    34. RequestBody body = RequestBody.create(mediaType, askJson.toJSONString());
    35. Request request = new Request.Builder()
    36. .url("https://aip.baidubce.com/rpc/2.0/nlp/v1/news_summary?charset=UTF-8&access_token=" + getAccessToken())
    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. return response.body().string();
    43. }
    44. }

  • 相关阅读:
    GUI+SQLServer考试系统
    形式逻辑简介
    VMware虚拟机 Centos7 配置静态IP和DNS
    数字化时代的探索,企业如何做好数字化转型?
    计算机网络---TCPIP网络编程实验
    基于随机无迹sigma点变异策略的改进哈里斯鹰优化算法
    22.11.25打卡 2022河南萌新联赛第(二)场:河南理工大学 AFJL
    在事件循环中使用暂停器
    bootstrap样式
    Markdown基本语法
  • 原文地址:https://blog.csdn.net/ftm_csdn/article/details/133531534