1,HTTP出口
方案 异步 JDK 额外依赖 特点 HttpURLConnection 【优点】Java内置,简单易用。对于简单的HTTP请求和响应处理非常合适。
【缺点】功能相对较少,不支持现代特性(如异步请求、连接池等)。API相对繁琐,处理复杂请求时代码冗长。不建议使用
java.net.http.httpclient √ 11 【优点】Java 11引入,支持异步请求、HTTP/2、WebSocket等现代特性。API设计较为简洁,使用流式处理。上一个的替代品
【缺点】仅在Java 11及以上版本可用,兼容性较差。在复杂配置时可能不如其他库灵活。
Apache HttpClient √ 8 √ 【优点】功能强大,支持连接池、认证、重定向等。创建一次,多线程复用。
【缺点】使用需要手动封装,手动关闭,Android已经舍弃采用OkHttp。
OkHttp √ √ 【优点】性能优越,支持HTTP/2、连接池等,适合移动端和高并发场景。简洁易用,提供强大的拦截器功能。
【缺点】使用需要手动封装,非单例模式。
Retrofit √ √ 【优点】基于okHttp,专为REST API设计,支持注解风格的请求定义。与Gson等库集成良好,简化数据解析。
【缺点】非单例模式
RestTemplate √ 【优点】Spring框架的一部分,适合在Spring应用中使用。提供多种请求方法的支持,易于集成,封装度高。
【缺点】随着Spring 5的推出,已被WebClient逐渐取代,可能会被弃用。不是非阻塞的,性能可能较低。没有连接池。
OpenFeign √ 8 √ 【优点】允许声明式地创建HTTP客户端,使用简单。与Spring Cloud集成良好,支持服务发现和负载均衡。支持多种客户端。
【缺点】默认的http是HttpURLConnection。
Forest √ √ 【优点】API设计清晰,使用注解方式简化了HTTP请求的构建;支持异步请求和连接池,适合高并发场景;支持HTTP/2、WebSocket等现代特性,功能全面;支持多种序列化/反序列化方式,方便处理不同格式的数据。
【缺点】社区支持不足。
【业界主流】 okHttp 组合 Retrofit:
- okHttp:在性能和灵活性方面表现出色,支持连接池和异步请求,适合需要高并发的场景。
- Retrofit:基于okHttp,提供声明式的API定义,使得处理RESTful服务变得简单,集成数据解析库(如Gson)也非常方便。
1.1,HttpURLConnection
【简介】HttpURLConnection是一个抽象类,提供了一种与HTTP服务器进行通信的方法。它是URL类的一部分,支持GET、POST等HTTP请求。
【涉及jar】HttpURLConnection类是Java标准库的一部分,通常不需要额外的JAR文件。
【使用方式】使用HttpURLConnection的基本步骤:
- 创建URL对象:
URL url = new URL("http://example.com");
- 打开连接:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- 设置请求方法:
connection.setRequestMethod("GET");
- 发送请求并获取响应:
int responseCode = connection.getResponseCode();
- 读取响应:通过InputStream读取。
【常用方法】
setRequestMethod(String method)
:设置请求方法(GET, POST等)。getResponseCode()
:获取响应状态码。getInputStream()
:获取响应内容。setRequestProperty(String key, String value)
:设置请求头。【优点】
- 简单易用,集成于Java标准库。
- 支持各种HTTP方法。
【缺点】
- 不支持异步操作。
- 配置和调试相对繁琐。
1.2,java.net.http.HttpClient
【简介】HttpClient提供了一个简化的API来发送HTTP请求和处理响应,支持异步和同步操作,并具有更好的性能和可扩展性。
【涉及jar】HttpClient是Java标准库的一部分,包含在Java 11及更高版本中,因此无需额外的JAR文件。
【使用方式】
- 创建HttpClient实例:
HttpClient client = HttpClient.newHttpClient();
- 构建请求:
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://example.com")).build();
- 发送请求并处理响应:
client.send(request, HttpResponse.BodyHandlers.ofString());
【常用方法】
newHttpClient()
:创建HttpClient实例。newBuilder()
:构建HttpRequest。send()
:发送请求并获取HttpResponse。sendAsync()
:异步发送请求。【优点】
- 支持异步编程,提高性能。
- API设计更简洁,易于使用。
- 支持HTTP/2协议。
【缺点】
- 只在Java 11及以上版本可用。
- 需要掌握新的API特性。
1.3,Apache HttpClient
【简介】Apache HttpClient提供了丰富的功能来执行HTTP请求,包括连接管理、身份验证、代理支持等,广泛用于Java应用中。
【涉及jar】
<dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version> </dependency>
【使用方式】
- 创建HttpClient实例:CloseableHttpClient client = HttpClients.createDefault();
- 构建请求:HttpGet request = new HttpGet("http://example.com");
- 发送请求并处理响应:CloseableHttpResponse response = client.execute(request);
【常用方法】
execute(HttpUriRequest request)
:执行请求。CloseableHttpResponse
:获取响应对象。setEntity(HttpEntity entity)
:设置请求体。setHeader(String name, String value)
:设置请求头。【优点】
- 功能强大,支持多种HTTP特性。
- 易于配置和扩展。
- 支持异步操作。
【缺点】
- 引入额外的依赖。
- 相比于Java标准库,学习曲线略陡。
1.4,OkHttp
【简介】OkHttp以其强大的性能和简单的API而闻名,支持连接池、透明的GZIP压缩、缓存以及异步请求等特性。
【涉及jar】
<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId><version>4.9.3</version> </dependency>
【使用方式】
- 创建OkHttpClient实例:OkHttpClient client = new OkHttpClient();
- 构建请求:
Request request = new Request.Builder().url("http://example.com").build();
- 发送请求并处理响应:
try (Response response = client.newCall(request).execute()) {String responseData = response.body().string(); }
【常用方法】
newCall(Request request)
:创建一个新的请求调用。execute()
:同步执行请求。enqueue(Callback callback)
:异步执行请求。addInterceptor(Interceptor interceptor)
:添加拦截器。【优点】
- 性能优越,支持HTTP/2。
- API设计简洁明了,易于使用。
- 提供强大的缓存和连接池机制。
【缺点】
- 需要额外的依赖。
- 初学者可能需要时间熟悉异步编程模式。
1.5,Retrofit
【简介】Retrofit简化了API请求的实现,使得网络调用变得更加高效且易于管理。它支持多种解析库,如Gson、Moshi等,并允许通过注解方式定义API接口。
【涉及jar】
<dependency><groupId>com.squareup.retrofit2</groupId><artifactId>retrofit</artifactId><version>2.9.0</version> </dependency> <dependency><groupId>com.squareup.retrofit2</groupId><artifactId>converter-gson</artifactId><version>2.9.0</version> </dependency>
【使用方式】
//创建Retrofit实例 Retrofit retrofit = new Retrofit.Builder().baseUrl("http://example.com/").addConverterFactory(GsonConverterFactory.create()).build(); //定义API接口 public interface ApiService {@GET("endpoint")Call<ResponseType> getData(); } //创建API服务并调用 ApiService apiService = retrofit.create(ApiService.class); Call<ResponseType> call = apiService.getData(); call.enqueue(new Callback<ResponseType>() {@Overridepublic void onResponse(Call<ResponseType> call, Response<ResponseType> response) {// 处理响应}@Overridepublic void onFailure(Call<ResponseType> call, Throwable t) {// 处理失败} });
【常用方法】
create(Class<T> service)
:创建API服务接口实例。enqueue(Callback<T> callback)
:异步请求,处理响应。execute()
:同步请求(不推荐在主线程中使用)。【优点】
- 使用简单,支持注解方式定义API。
- 支持多种数据解析库。
- 提供强大的异步请求处理。
【缺点】
- 对于简单请求,可能显得过于复杂。
- 引入额外的依赖。
1.6,RestTemplate
【简介】RestTemplate是Spring Web模块的一部分,旨在简化与RESTful服务的交互,支持多种HTTP方法(GET、POST、PUT、DELETE等),并提供了便捷的API。
【涉及jar】
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency>
【使用方式】
- 创建RestTemplate实例:RestTemplate restTemplate = new RestTemplate();
- 发送请求并处理响应:
String url = "http://example.com/api/data"; ResponseEntity<ResponseType> response = restTemplate.getForEntity(url, ResponseType.class);
【常用方法】
getForEntity(String url, Class<T> responseType)
:发送GET请求并返回ResponseEntity。postForEntity(String url, Object request, Class<T> responseType)
:发送POST请求并返回ResponseEntity。exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType)
:发送任意类型请求。【优点】
- 易于使用,特别是对于Spring应用。
- 支持多种HTTP方法。
- 集成了Spring的异常处理机制。
【缺点】
- 主要是同步请求,不支持异步操作。
- 对于复杂请求,可能需要更多配置。
1.7,OpenFeign
【简介】Retrofit简化了API请求的实现,使得网络调用变得更加高效且易于管理。它支持多种解析库,如Gson、Moshi等,并允许通过注解方式定义API接口。
【涉及jar】
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
【使用方式】
//启用Feign客户端: 在Spring Boot应用的主类上添加注解 @EnableFeignClients public class Application {public static void main(String[] args) {SpringApplication.run(Application.class, args);} }//定义Feign客户端接口 @FeignClient(name = "example-client", url = "http://example.com") public interface ExampleClient {@GetMapping("/api/data")ResponseType getData(); }//注入Feign客户端并使用 @Autowired private ExampleClient exampleClient;public void someMethod() {ResponseType response = exampleClient.getData(); }
【常用方法】
@FeignClient
:定义Feign客户端。@GetMapping
,@PostMapping
等:定义HTTP请求方法。ResponseType
:定义返回值类型。【优点】
- 声明式编程,代码更简洁。
- 集成Spring生态系统,易于使用。
- 支持多种请求参数和响应处理。
【缺点】
- 对于简单的HTTP请求,可能显得复杂。
- 需要对Spring Cloud有一定的了解。
1.8,forest
【简介】Forest是一个轻量级的Java HTTP客户端,主要用于简化与HTTP服务器的交互。
【涉及jar】
<dependency><groupId>com.dromara</groupId><artifactId>forest-spring-boot-starter</artifactId> </dependency>
【使用方式】
@ForestClient
: 注解用于创建HTTP客户端。@RequestMapping
: 定义HTTP请求类型和路径。- 支持GET、POST、PUT等HTTP方法。
【优点】
- 简单易用,减少样板代码。
- 支持多种请求类型和参数处理。
【缺点】
- 相较于其他成熟框架(如Apache HttpClient),可能功能不够丰富。
- 文档和社区支持相对较少。
2,HTTP入口
2.1,Spring MVC
@RequestMapping注解:使用@RestController注解定义控制器,结合@RequestMapping或@GetMapping、@PostMapping等注解处理不同的HTTP请求。通过@RequestParam、@PathVariable等获取请求参数。
- 功能全面,支持依赖注入,易于集成其他Spring模块。
@Controller public class UserController {@RequestMapping("/login")public String login(){...} }
2.2,Servlet
使用Java EE的Servlet API,可以通过 HttpServlet 类来处理HTTP请求。
- 基础功能强大,兼容性好,性能高。
- 开发相对繁琐,缺乏现代化特性。
创建一个实现HttpServlet的类,重写doGet()和doPost()方法来处理请求。使用HttpServletRequest获取请求数据。
public class MyHttpServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 设置响应内容类型response.setContentType("text/html;charset=UTF-8");// 获取请求参数String name = request.getParameter("name");try (PrintWriter out = response.getWriter()) {out.println("<html><body>");out.println("<h1>Hello, " + (name != null ? name : "World") + "!</h1>");out.println("</body></html>");}}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {...} }
2.3,AX-RS
使用@Path和其他相关注解定义资源和HTTP方法,方便构建RESTful服务。可以与多种实现(如 Jersey、RESTEasy)结合使用。
- 设计简单,符合RESTful标准,适合构建API。
- 需要额外学习相关实现(如Jersey)。
@Path("/greet") public class GreetingResource {@GET@Produces(MediaType.TEXT_HTML)public Response greet(@QueryParam("name") String name) {String greeting = "Hello, " + (name != null ? name : "World") + "!";return Response.ok("<html><body><h1>" + greeting + "</h1></body></html>").build();}@POST@Path("/message")@Consumes(MediaType.APPLICATION_FORM_URLENCODED)@Produces(MediaType.TEXT_HTML)public Response receiveMessage(@FormParam("message") String message) {String responseMessage = "Received message: " + (message != null ? message : "No message");return Response.ok("<html><body><h1>" + responseMessage + "</h1></body></html>").build();} }
2.4,Spark
Spark是一个轻量级的Java Web框架,旨在快速构建Web应用程序。它提供了简单的API,允许开发者快速定义路由和处理HTTP请求,适合小型应用和微服务。
- 轻量级,易于上手,适合小型应用。
- 功能相对有限,不适合大型项目。
public class SimpleSparkApp {public static void main(String[] args) {// 设置GET请求的路由get("/greet", (req, res) -> {String name = req.queryParams("name");return "Hello, " + (name != null ? name : "World") + "!";});// 设置POST请求的路由post("/message", (req, res) -> {String message = req.queryParams("message");return "Received message: " + (message != null ? message : "No message");});} }
2.5,Vert.x
Vert.x是一个异步的、事件驱动的应用程序框架,适用于构建高性能的Web应用和微服务。它支持多种编程语言(如Java、Kotlin、JavaScript等),并提供了强大的模块系统和支持多种协议(如HTTP、TCP、WebSocket等)。
- 高性能,支持异步编程,适合高并发应用。
@RestController @RequestMapping("/api") class ApiController {private final Vertx vertx;public ApiController(Vertx vertx) {this.vertx = vertx;}@PostMapping("/async")public void asyncOperation(@RequestBody String message) {vertx.executeBlocking(promise -> {// 模拟长时间操作try {Thread.sleep(2000);promise.complete("Processed: " + message);} catch (InterruptedException e) {promise.fail(e);}}, result -> {if (result.succeeded()) {System.out.println(result.result());} else {System.err.println("Failed: " + result.cause());}});} }@Bean public Vertx vertx() {return Vertx.vertx(); }