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


}
相关推荐
振鹏Dong6 分钟前
Spring事务管理机制深度解析:从JDBC基础到Spring高级实现
java·后端·spring
信码由缰12 分钟前
Java包装类:你需要掌握的核心要点
java
小凯 ོ1 小时前
实战原型模式案例
java·后端·设计模式·原型模式
Dcs1 小时前
性能提升超100%!PostgreSQL主键选择大变革:UUIDv7能否终结v4的统治?
java
渣哥1 小时前
没有 Optional,Java 程序员每天都在和 NullPointerException 打架
java
智_永无止境1 小时前
Java集合操作:Apache Commons Collections4启示录
java·apache
悟能不能悟2 小时前
java去图片水印的方法
java·人工智能·python
从零开始学习人工智能2 小时前
PDFMathTranslate:让科学PDF翻译不再难——技术原理与实践指南
java·开发语言·pdf
一水鉴天2 小时前
整体设计 修订 之1 三“先”之“基” 与范畴重构:康德先验哲学的批判性程序化实现
java·人工智能·算法