当前位置: 首页 > news >正文

java实现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请求,并打印出响应结果。

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • Utilize webcam to capture photo with camera
  • Leetcode C语言习题
  • 头歌:共享单车之数据可视化
  • Docker之数据卷和Dockerfile
  • 2024 年最新使用 Wechaty 开源框架搭建部署微信机器人(微信群智能客服案例)
  • 前端二维码工具小程序产品使用说明书
  • RISC-V特权架构 - 模式切换与委托
  • Leetcode 68. 文本左右对齐
  • GFS分布式 文件系统
  • 前端小白的学习之路(Vue2 一)
  • Excel全套213集教程
  • 【数据结构】考研真题攻克与重点知识点剖析 - 第 5 篇:树与二叉树
  • Rust 实现线程安全的 Lock Free 计数器
  • Springboot使用教程
  • c语言:操作符
  • 【译】JS基础算法脚本:字符串结尾
  • Android优雅地处理按钮重复点击
  • JAVA 学习IO流
  • JavaScript设计模式与开发实践系列之策略模式
  • Laravel Mix运行时关于es2015报错解决方案
  • SpiderData 2019年2月16日 DApp数据排行榜
  • text-decoration与color属性
  • Xmanager 远程桌面 CentOS 7
  • 测试如何在敏捷团队中工作?
  • 缓存与缓冲
  • 前嗅ForeSpider教程:创建模板
  • 如何邀请好友注册您的网站(模拟百度网盘)
  • 如何在GitHub上创建个人博客
  • 使用前端开发工具包WijmoJS - 创建自定义DropDownTree控件(包含源代码)
  • 数据仓库的几种建模方法
  • 腾讯大梁:DevOps最后一棒,有效构建海量运营的持续反馈能力
  • 我感觉这是史上最牛的防sql注入方法类
  • 一起来学SpringBoot | 第十篇:使用Spring Cache集成Redis
  • Salesforce和SAP Netweaver里数据库表的元数据设计
  • ​水经微图Web1.5.0版即将上线
  • # 再次尝试 连接失败_无线WiFi无法连接到网络怎么办【解决方法】
  • #职场发展#其他
  • (1)bark-ml
  • (11)MATLAB PCA+SVM 人脸识别
  • (附源码)springboot宠物医疗服务网站 毕业设计688413
  • (个人笔记质量不佳)SQL 左连接、右连接、内连接的区别
  • (精确度,召回率,真阳性,假阳性)ACC、敏感性、特异性等 ROC指标
  • (强烈推荐)移动端音视频从零到上手(下)
  • (十七)Flink 容错机制
  • (四)七种元启发算法(DBO、LO、SWO、COA、LSO、KOA、GRO)求解无人机路径规划MATLAB
  • (原創) 如何解决make kernel时『clock skew detected』的warning? (OS) (Linux)
  • (转)http-server应用
  • (转)linux自定义开机启动服务和chkconfig使用方法
  • .mat 文件的加载与创建 矩阵变图像? ∈ Matlab 使用笔记
  • .NET DataGridView数据绑定说明
  • .net mvc actionresult 返回字符串_.NET架构师知识普及
  • .NET 使用 ILMerge 合并多个程序集,避免引入额外的依赖
  • .Net 知识杂记
  • .NET 直连SAP HANA数据库
  • .NET 中各种混淆(Obfuscation)的含义、原理、实际效果和不同级别的差异(使用 SmartAssembly)