调用okhttp3的案例代码

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.10.0</version>
        </dependency>
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();
    }


}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值