调用okhttp3的案例代码

XML 复制代码
<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.10.0</version>
        </dependency>
java 复制代码
package com.ftm.main.service.impl;

import com.alibaba.fastjson2.JSONObject;
import okhttp3.*;
import org.springframework.stereotype.Service;

@Service("SampleServiceImpl")
public class SampleServiceImpl {

    public static final String API_KEY = "LWArx3rK8t5jaDWgYK0PAhUn";
    public static final String SECRET_KEY = "EHUudzDvELkgWXEGrDkRmcGKRE8qYkRx";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    /**
     * 从用户的AK,SK生成鉴权签名(Access Token)
     *
     * @return 鉴权签名(Access Token)
     * @throws Exception IO异常
     */
    public String getAccessToken() throws Exception {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();


        return JSONObject.parseObject(response.body().string()).getString("access_token");
    }



    public String getNewsSummary(String askTitle,String askContent) throws Exception{
        MediaType mediaType = MediaType.parse("application/json");

        JSONObject askJson = new JSONObject();
        askJson.put("max_summary_len", "200");
        askJson.put("title",askTitle);
        askJson.put("content",askContent);

        RequestBody body = RequestBody.create(mediaType, askJson.toJSONString());
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/nlp/v1/news_summary?charset=UTF-8&access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return response.body().string();
    }


}
相关推荐
NE_STOP6 小时前
Vide Coding--AI编程工具的选择
java
码云数智-园园6 小时前
C++20 Modules 模块详解
java·开发语言·spring
程序员黑豆6 小时前
JDK 下载安装与配置详细教程
java·前端·ai编程
小宇宙Zz7 小时前
Maven依赖冲突
java·服务器·maven
swordbob7 小时前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
咖啡八杯7 小时前
GoF设计模式——享元模式
java·spring·设计模式·享元模式
十五喵源码网7 小时前
基于springboot2+vue2的租房管理系统
java·毕业设计·springboot·论文笔记
摇滚侠7 小时前
IDEA 创建 Java 项目 手动整合 SSM 框架
java·ide·intellij-idea
源分享7 小时前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Flittly8 小时前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring