调用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();
    }


}
相关推荐
customer087 小时前
【开源免费】基于SpringBoot+Vue.JS体育馆管理系统(JAVA毕业设计)
java·vue.js·spring boot·后端·开源
Miketutu8 小时前
Spring MVC消息转换器
java·spring
乔冠宇8 小时前
Java手写简单Merkle树
java·区块链·merkle树
LUCIAZZZ9 小时前
简单的SQL语句的快速复习
java·数据库·sql
komo莫莫da9 小时前
寒假刷题Day19
java·开发语言
S-X-S10 小时前
算法总结-数组/字符串
java·数据结构·算法
linwq810 小时前
设计模式学习(二)
java·学习·设计模式
桦说编程11 小时前
CompletableFuture 超时功能有大坑!使用不当直接生产事故!
java·性能优化·函数式编程·并发编程
@_@哆啦A梦11 小时前
Redis 基础命令
java·数据库·redis
字节全栈_rJF12 小时前
性能测试 —— Tomcat监控与调优:status页监控_tomcat 自带监控
java·tomcat