java实现API服务及请求客户端

news/2025/2/9 0:23:49 标签: java, spring, boot, api, 请求, 客户端, 服务端

要实现一个Java API服务以及对应的请求客户端,可以按照以下步骤操作:

步骤一:创建API服务端使用Java开发API服务端通常会涉及构建RESTful API,并选择一个Web框架(如Spring Boot、JAX-RS等)来简化开发过程。这里以Spring Boot为例,展示如何创建一个简单的API服务。

步骤二:创建API请求客户端为了与上述API服务进行交互,你可以使用多种方式编写客户端代码。

具体代码如下:采用spring boot

服务端(Spring Boot应用)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.example</groupId>
<artifactId>api-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
public class User {
private Long id;
private String name;
private String email;

// 构造函数、getter和setter省略
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/users")
public class UserService {

@GetMapping("/{id}")
public User getUser(@PathVariable Long id) {
// 实现从数据库或其他数据源获取用户逻辑,这里仅作示例返回一个假数据
return new User(id, "John Doe", "john.doe@example.com");
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
运行DemoApplication,服务端将在本地的8080端口启动。客户端(使用Apache HttpClient)创建一个新的Java项目,添加Apache HttpClient依赖(如httpclient和httpcore),然后编写如下代码: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;

public class HttpClientApiClient {

public static void main(String[] args) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet request = new HttpGet("http://localhost:8080/users/1");

CloseableHttpResponse response = httpClient.execute(request);
try {
if (response.getStatusLine().getStatusCode() == 200) {
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println("Response: " + responseBody); // 输出响应内容
} else {
System.err.println("Error: " + response.getStatusLine().toString());
}
} finally {
response.close();
}
} finally {
httpClient.close();
}
}
}
客户端(使用Spring RestTemplate)如果客户端也是一个Spring Boot应用,添加Spring Web依赖,然后编写如下代码:import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateApiClient {

public static void main(String[] args) {
SpringApplication.run(RestTemplateApiClient.class, args);

RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForObject("http://localhost:8080/users/1", User.class);
System.out.println("Response: " + user);
}
}
分别运行HttpClientApiClient和RestTemplateApiClient,它们将向本地的API服务端发送GET请求,并打印出响应结果。


http://www.niftyadmin.cn/n/5479410.html

相关文章

探索K-近邻算法(KNN):原理、实践应用与文本分类实战

第一部分&#xff1a;引言与背景 KNN算法在机器学习领域的重要性及其地位 KNN算法作为机器学习中的基石之一&#xff0c;由于其概念直观、易于理解并且不需要复杂的模型训练过程&#xff0c;被广泛应用于多种场景。它在监督学习中占据着特殊的位置&#xff0c;尤其适用于实时…

面试准备 集合 List

ArrayList 底层实现 使用Object[] 动态数组进行存储 特性 支持存储null值非线程安全支持快速访问 初始化方法 无参–返回一个空的列表&#xff08;DEFAULTCAPACITY_EMPTY_ELEMENTDATA&#xff09;指定初始容量&#xff1a; new ArrayList(20);指定集合 new ArrayList(col…

栈的详解和例题(力扣有效括号)

感谢各位大佬的光临&#xff0c;希望和大家一起进步&#xff0c;望得到你的三连&#xff0c;互三支持&#xff0c;一起进步 个人主页&#xff1a;LaNzikinh-CSDN博客 收入专栏:初阶数据结构_LaNzikinh篮子的博客-CSDN博客 文章目录 前言一.什么是栈二.栈的实现三.例题&#xff…

网络安全---Packet Tracer - 配置扩展 ACL

一、实验目的 在Windows环境下利用Cisco Packet Tracer进行 配置防火墙操作。 二、实验环境 1.Windows10、Cisco Packet Tracer 8.2 2.相关的环境设置 在最初的时候&#xff0c;我们已经得到了搭建好的拓扑模型&#xff0c;利用已经搭建好的拓扑模型&#xff0c;进行后续的…

使用UDP完成网络单词查询,利用dict数据库

【注】UDP的优缺点&#xff1a; 1&#xff1a;传输效率高 2&#xff1a;易出现数据丢失 3&#xff1a;以数据报的形式传输 思路&#xff1a; step1&#xff1a;获取客户端请求 step2&#xff1a;查询单词 step3&#xff1a;响应客户端 Client.py from socket import *SERVICE_…

C语言每日一题(66)三数之和

题目链接 力扣15.三数之和 题目描述 给你一个整数数组 nums &#xff0c;判断是否存在三元组 [nums[i], nums[j], nums[k]] 满足 i ! j、i ! k 且 j ! k &#xff0c;同时还满足 nums[i] nums[j] nums[k] 0 。请 你返回所有和为 0 且不重复的三元组。 注意&#xff1a;答…

(26)4.7 字符函数和字符串函数

#include<stdio.h> #include<string.h> #include<assert.h> //int my_strcmp(const char* str1, const char* str2) //{ // assert(str1 && str2);//指针有效性&#xff0c;不能为空指针 // while (*str1 *str2) // { // if (*str1…

linux启动流程(s3c2400)

概述 大致流程&#xff1a;内核&#xff08;kernel&#xff09;都是由bootloader程序引导启动的&#xff0c;所以我们应该先烧进去bootloader程序。然后可以通过保存的内核代码或者通过远程连接&#xff08;nfs/tftp&#xff09;的主机下载再运行&#xff0c;再挂载根文件系统。…