<groupId>com.squareup.okhttp3groupId>
<artifactId>okhttpartifactId>
package com.ftm.main.service.impl;
import com.alibaba.fastjson2.JSONObject;
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();
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")
.addHeader("Content-Type", "application/x-www-form-urlencoded")
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())
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
Response response = HTTP_CLIENT.newCall(request).execute();
return response.body().string();