10:获取目标网站标题功能
依赖库
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>${jsoup.version}</version>
</dependency>
URL 标题控制层 - UrlTitleController(admin服务)
@RestController(value = "urlTitleControllerByAdmin")
@RequiredArgsConstructor
public class UrlTitleController {
private final ShortLinkActualRemoteService shortLinkActualRemoteService;
@GetMapping("/api/short-link/admin/v1/title")
public Result<String> getTitleByUrl(@RequestParam("url") String url) {
return shortLinkActualRemoteService.getTitleByUrl(url);
}
}
短链接中台远程调用服务 - shortLinkActualRemoteService
@FeignClient(
value = "short-link-project",
url = "${aggregation.remote-url:}",
configuration = OpenFeignConfiguration.class
)
public interface ShortLinkActualRemoteService {
@GetMapping("/api/short-link/v1/title")
Result<String> getTitleByUrl(@RequestParam("url") String url);
}
根据 URL 获取对应网站的标题 - UrlTitleController (project服务)
@RestController
@RequiredArgsConstructor
public class UrlTitleController {
private final UrlTitleService urlTitleService;
@GetMapping("/api/short-link/v1/title")
public Result<String> getTitleByUrl(@RequestParam("url") String url) {
return Results.success(urlTitleService.getTitleByUrl(url));
}
}
URL 标题接口实现层 - UrlTitleServiceImpl
@Service
public class UrlTitleServiceImpl implements UrlTitleService {
@SneakyThrows
@Override
public String getTitleByUrl(String url) {
URL targetUrl = new URL(url);
HttpURLConnection connection = (HttpURLConnection) targetUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
Document document = Jsoup.connect(url).get();
return document.title();
}
return "Error while fetching title.";
}
}