前端一般通过Ajax来调用,后端调用的方式还是挺多的,比如HttpURLConnection,HttpClient,Spring的RestTemplate
服务端代码如下:
服务端接口请求的URL:http://localhost:8080/rest/user/getUser/xiaoming/18,设定请求方式为GET
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.demo.restful.service.impl; import com.demo.restful.model.User; import com.demo.restful.service.UserService; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** * @Author: * @Date: 2019/1/8 11:37 */ @Path ( "user" ) public class UserServiceImpl implements UserService { @Override @GET @Path ( "getUser/{name}/{age}" ) @Produces (MediaType.APPLICATION_JSON) public String getUser( @PathParam ( "name" ) String name, @PathParam ( "age" ) Integer age) { return new User(name,age).toString(); } } |
客户端的三种请求方式如下:
注:以下demo都是以GET请求为例
1.HttpURLConnection(首先需要引入httpclient包)
1 2 3 4 5 | <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version> 4.5 . 6 </version> </dependency> |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package com.demo.restful; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * @Author: * @Date: 2019/1/9 11:12 */ public class HttpUrlConnectionTest { public static void main(String[] args) throws Exception { String url = "http://localhost:8080/rest/user/getUser/xiaoming/18" ; URL serverUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) serverUrl.openConnection(); connection.setRequestMethod( "GET" ); if (connection.getResponseCode() != 200 ) { throw new RuntimeException( "HTTP GET Request Failed with Error code : " + connection.getResponseCode()); } BufferedReader responseBuffer = new BufferedReader( new InputStreamReader((connection.getInputStream()))); String output; System.out.println( "Output from Server: \n" ); while ((output = responseBuffer.readLine()) != null ) { System.out.println(output); } connection.disconnect(); } } |
测试结果
2.HttpClient(首先需要引入httpclient包,POM同上)
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | package com.demo.restful; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClients; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.stream.Collectors; /** * @Author: * @Date: 2019/1/9 11:42 */ public class HttpClientTest { public static void main(String[] args) throws Exception { HttpClient httpClient = HttpClients.createDefault(); HttpGet httpGet = new HttpGet( "http://localhost:8080/rest/user/getUser/xiaoming/18" ); HttpResponse execute = httpClient.execute(httpGet); HttpEntity entity = execute.getEntity(); System.out.println(entity); String result = new BufferedReader( new InputStreamReader(entity.getContent())) .lines().collect(Collectors.joining( "\n" )); System.out.println(result); } } |
测试结果
3.RestTemplate(首先需要引入spring-webmvc包)
1 2 3 4 5 6 | <!-- https: //mvnrepository.com/artifact/org.springframework/spring-web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version> 5.1 . 3 .RELEASE</version> </dependency> |
测试代码
第一步:配置web.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>restful-client</servlet-name> <servlet- class >org.springframework.web.servlet.DispatcherServlet</servlet- class > <init-param> <param-name>contextConfigLocation</param-name> <param-value>spring.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>restful-client</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app> |
第二步:配置Spring注解扫描
1 2 3 4 5 6 7 8 9 10 11 | <?xml version= "1.0" encoding= "UTF-8" ?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns:context= "http://www.springframework.org/schema/context" xsi:schemaLocation=" http: //www.springframework.org/schema/beans http: //www.springframework.org/schema/beans/spring-beans-3.0.xsd http: //www.springframework.org/schema/context http: //www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 启用注解 --> <context:component-scan base- package = "com.demo.restful.controller" /> </beans> |
第三步:编写controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | package com.demo.restful.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; /** * @Author: * @Date: 2019/1/9 14:56 */ @Controller public class RestTemplateController { @Autowired private RestTemplate restTemplate; //手动将RestTemplate加入Spring容器中 @Bean public RestTemplate restTemplate(){ return new RestTemplate(); } @RequestMapping ( "/getUser.json" ) @ResponseBody public String getUser(){ String url = "http://localhost:8080/rest/user/getUser/xiaoming/18" ; String forObject = restTemplate.getForObject(url, String. class ); return forObject; } } |
浏览器运行结果
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
2015-01-14 plsql中文乱码