Spring Boot 接入百度在线搜索
在Spring Boot应用中接入百度的在线搜索,通常是通过调用百度提供的搜索API来实现的。以下是详细的接入步骤和示例代码:
一、准备工作
- 注册百度开发者账号:访问百度开放云平台,注册并登录开发者账号。
- 创建应用:在百度开放云平台上创建新应用,获取API Key和Secret Key。这些密钥将用于后续的API调用身份验证。
- 了解API文档:仔细阅读百度搜索API的官方文档,了解API的功能、调用方式、参数说明以及返回结果格式。
二、项目配置
- 添加依赖:在Spring Boot项目的pom.xml文件中添加必要的依赖,如Spring Web用于处理HTTP请求,以及可能需要的JSON解析库(如Jackson)。
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 如果需要,可以添加JSON解析库的依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
</dependencies>
- 配置API参数:在application.properties或application.yml文件中配置百度API的密钥和基础URL。
# application.properties
baidu.api.key=你的API_Key
baidu.api.secret=你的Secret_Key
baidu.search.url=https://api.baidu.com/search/v1.0?q=
三、核心代码实现
- 构造HTTP请求工具类:编写一个工具类,用于构造HTTP请求并发送到百度搜索API。
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
@Service
public class BaiduSearchService {
@Value("${baidu.api.key}")
private String apiKey;
@Value("${baidu.search.url}")
private String searchUrl;
public String search(String keyword) throws IOException {
String encodedKeyword = URLEncoder.encode(keyword, StandardCharsets.UTF_8);
String fullUrl = searchUrl + encodedKeyword + "&ak=" + apiKey;
CloseableHttpClient client = HttpClients.createDefault();
HttpGet request = new HttpGet(fullUrl);
try (CloseableHttpResponse response = client.execute(request)) {
return EntityUtils.toString(response.getEntity());
}
}
}
- 定义REST接口:在Controller层定义一个REST接口,用于接收前端发送的搜索请求,并调用Service层的方法进行搜索。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/search")
public class SearchController {
@Autowired
private BaiduSearchService searchService;
@GetMapping
public ResponseEntity<?> search(@RequestParam String q) {
try {
String result = searchService.search(q);
return ResponseEntity.ok(result);
} catch (Exception e) {
return ResponseEntity.status(500).body("搜索服务异常");
}
}
}
四、测试验证
- 发送测试请求:使用浏览器或Postman等工具发送GET请求到
http://localhost:8080/api/search?q=你的搜索关键词,验证是否能够正确获取搜索结果。 - 处理返回结果:根据百度API的响应结构,定义对应的Java实体类来解析返回的JSON数据,并在前端进行展示。
本文来自博客园,作者:蓝迷梦,转载请注明原文链接:https://www.cnblogs.com/hewei-blogs/articles/19116619

浙公网安备 33010602011771号