企业做电商网站有哪些内容,小规模公司需要交哪些税,企业网站模板下载,精品课程网站建设论文环境#xff1a;SpringBoot.3.3.0 1、简介
在项目中调用第三方接口是日常开发中非常常见的。调用方式的选择通常遵循公司既定的技术栈和架构规范#xff0c;以确保项目的一致性和可维护性。无论是RESTful API调用、Feign声明式HTTP客户端、Apache HttpClient等调用方式… 环境SpringBoot.3.3.0 1、简介
在项目中调用第三方接口是日常开发中非常常见的。调用方式的选择通常遵循公司既定的技术栈和架构规范以确保项目的一致性和可维护性。无论是RESTful API调用、Feign声明式HTTP客户端、Apache HttpClient等调用方式每种方式都有其适用场景和优势选择最适合的方式将有助于提高开发效率和系统性能。接下来将全面介绍10种第三方接口调用的实现方式。
2、实战案例
2.1 JDK URL
URL url URI.create(http://localhost:8002/api/data).toURL() ;
URLConnection connection url.openConnection() ;
connection.setDoInput(true) ;
connection.setDoOutput(true) ;
InputStream inputStream connection.getInputStream() ;
String ret StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8) ;
System.out.println(ret) ;该种方式比较麻烦上面代码还没有入参情况如果比较复杂的接口那么代码编写也比较费时。
2.2 JDK HttpClient
URI uri URI.create(http://localhost:8002/api/data) ;
HttpClient client HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(3)).executor(Executors.newCachedThreadPool()).build() ;
HttpRequest request HttpRequest.newBuilder(uri).GET().build();
HttpResponseString response client.send(request, BodyHandlers.ofString()) ;
System.out.println(response.body()) ;HttpClient类是在JDK11中提供感觉也挺麻烦不过它的可配置性更好了。
2.3 Apache Http Client
HttpGet httpget new HttpGet(http://localhost:8002/api/data) ;
CloseableHttpClient client HttpClients.custom().build() ;
HttpClientResponseHandlerString responseHandler new BasicHttpClientResponseHandler() ;
String ret client.execute(httpget, responseHandler) ;
System.out.println(ret) ;Apache HttpClient 5是一个支持HTTP/2、高度可定制、支持异步请求的开源HTTP工具包提供了丰富的API和扩展特性。异步请求方式
CloseableHttpAsyncClient client HttpAsyncClients.custom().build() ;
client.start() ;
SimpleHttpRequest request SimpleRequestBuilder.get().setHttpHost(HttpHost.create(http://localhost:8002)).setPath(/api/data).build() ;
FutureCallbackSimpleHttpResponse callback new FutureCallbackSimpleHttpResponse() {Overridepublic void failed(Exception ex) {System.err.printf(请求失败: %s%n, ex.getMessage()) ;}Overridepublic void completed(SimpleHttpResponse result) {System.out.printf(当前线程: %s, 请求完成...%n, Thread.currentThread().getName()) ;}public void cancelled() {}
};
FutureSimpleHttpResponse future client.execute(request, callback) ;
System.out.println(new String(future.get().getBodyBytes(), StandardCharsets.UTF_8)) ;
client.close(CloseMode.GRACEFUL) ;Apache Client功能还是非常强大的。
2.4 OkHttp
OkHttp是一个高效的HTTP客户端:
HTTP/2 支持允许对同一主机的所有请求共享一个套接字。连接池可减少请求延迟如果 HTTP/2 不可用。透明GZIP缩小了下载大小。响应缓存可完全避免网络重复请求。
使用 OkHttp 非常简单。其请求/响应 API 采用流畅的构建器和不变性设计。它既支持同步阻塞调用也支持带回调的异步调用。
URL url URI.create(http://localhost:8002/api/data).toURL() ;
OkHttpClient client new OkHttpClient();
Request request new Request.Builder().url(url).build() ;
try (Response response client.newCall(request).execute()) {System.out.println(response.body().string()) ;
}异步请求
URL url URI.create(http://localhost:8002/api/data).toURL() ;
OkHttpClient client new OkHttpClient();
Request request new Request.Builder().url(url).build();
client.newCall(request).enqueue(new Callback() {public void onResponse(Call call, Response response) throws IOException {System.out.printf(当前线程: %s, 内容: %s%n, Thread.currentThread().getName(), response.body().string()) ;}public void onFailure(Call call, IOException e) {System.err.printf(请求失败: %s%n, e.getMessage()) ;}
}) ;2.5 RestTemplate
RestTemplate是我们项目中最为常用的接口调用方式了它以经典 Spring Template 类的形式为 HTTP 客户端库提供了高级 API。
RestTemplate restTemplate new RestTemplate() ;
Map ret restTemplate.getForObject(URI.create(http://localhost:8002/api/data), Map.class) ;
System.out.println(ret) ;通过RestTemplateBuilder可以对RestTemplate提供更多的配置。
RestTemplate restTemplate new RestTemplateBuilder()// 设置超时时间.setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(5))// 设置拦截器.interceptors(List.of()).build() ;
Map ret restTemplate.getForObject(URI.create(http://localhost:8002/api/data), Map.class) ;
System.out.println(ret) ;注默认情况下RestTemplate是通过JDK URL实现接口访问我们可以自定义设置Apache Http或OKHttp实现。
2.6 WebClient
RestTemplate 的替代方案支持同步、异步和流场景。WebClient 支持以下功能
非阻塞IO反应流背压用较少的硬件资源实现高并发利用 Java 8 lambdas 的函数式流畅应用程序接口支持同步和异步交互向服务器传输数据流或从服务器向下传输数据流
WebClient 需要一个 HTTP 客户端库来执行请求。内置的支持包括
Reactor NettyJDK HttpClientJetty Reactive HttpClientApache HttpComponents
其他可以通过ClientHttpConnector插入。
如下示例
WebClient client WebClient.create(http://localhost:8002);
client.get().uri(/api/data)// 获取结果.retrieve().bodyToMono(String.class).subscribe(System.out::println) ;更多配置超时/错误
HttpClient httpClient HttpClient.create().option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 10000) ;
WebClient client WebClient.builder().clientConnector(new ReactorClientHttpConnector(httpClient)).build() ;
client.get().uri(http://localhost:8002/api/data).retrieve().onStatus(HttpStatusCode::is4xxClientError, resp - Mono.error(new RuntimeException(客户端请求错误))).bodyToMono(String.class).subscribe(System.out::println) ;
System.in.read() ;通过WebClient#builder可以进行更多的配置信息。
2.7 RestClient
RestClient是Spring6.1起添加的新的API。创建或构建后RestClient 可由多个线程安全使用。
RestClient client RestClient.create() ;
ParameterizedTypeReferenceMapString, Object bodyType new ParameterizedTypeReferenceMapString, Object() {} ;
MapString, Object ret client.get().uri(URI.create(http://localhost:8002/api/data)).retrieve().body(bodyType) ;还可以通过RestClient#builder
RestClient client RestClient.builder()// 设置请求Header.defaultHeader(x-api-token, aaabbbccc111222)// 设置拦截器.requestInterceptor((request, body, execution) - execution.execute(request, body)).baseUrl(http://localhost:8002).build() ;通过builder方式你还可以进行更多的设置具体查看API。
2.8 Http Interface
将 HTTP 服务定义为带有 HttpExchange 方法的 Java 接口。你可以将这样的接口传递给 HttpServiceProxyFactory创建一个代理通过 HTTP 客户端如 RestClient 或 WebClient执行请求。
// 接口定义
public interface RemoteClient {GetExchange(/api/data)MapString, Object queryInfo() ;
}
// 执行调用
RestClient restClient RestClient.builder().baseUrl(http://localhost:8002).build() ;
RestClientAdapter adapter RestClientAdapter.create(restClient) ;
HttpServiceProxyFactory factory HttpServiceProxyFactory.builderFor(adapter).build() ;RemoteClient client factory.createClient(RemoteClient.class);
System.out.println(client.queryInfo()) ;上面调用通过RestClient进行你也可以换成RestTemplate。
2.9 OpenFeign
注意这里是OpenFeign可不是Spring Cloud OpenFeignSpring Cloud openfeign对OpenFeign进行了包装所以在使用上是有差别的。
引入依赖
dependencygroupIdio.github.openfeign/groupIdartifactIdfeign-core/artifactIdversion13.2.1/version
/dependency示例代码
// 接口定义
public interface RemoteClient {RequestLine(GET /api/data)MapString, Object queryInfo() ;
}
// 接口调用
RemoteClient client Feign.builder().decoder(new JacksonDecoder()).target(RemoteClient.class, http://localhost:8002) ;
MapString, Object ret client.queryInfo() ;OpenFeign还是至其他很多的注解如ParamHeadersBody等。
2.10 Gateway Proxy
引入依赖
dependencygroupIdorg.springframework.cloud/groupIdartifactIdspring-cloud-gateway-mvc/artifactId
/dependency代码示例
private URI uri URI.create(http://localhost:8002);GetMapping(/api)
public ResponseEntity? proxy(ProxyExchangebyte[] proxy) throws Exception {return proxy.uri(String.format(%s%s, uri.toString(), /api/data)).get() ;
}在上面的方法中通过ProxyExchange进行远程接口的调用。
文章来源Spring全家桶实战案例源码 文章转载自: http://www.morning.rcyrm.cn.gov.cn.rcyrm.cn http://www.morning.cwlxs.cn.gov.cn.cwlxs.cn http://www.morning.dfhkh.cn.gov.cn.dfhkh.cn http://www.morning.vattx.cn.gov.cn.vattx.cn http://www.morning.gtxrw.cn.gov.cn.gtxrw.cn http://www.morning.poapal.com.gov.cn.poapal.com http://www.morning.dktyc.cn.gov.cn.dktyc.cn http://www.morning.txltb.cn.gov.cn.txltb.cn http://www.morning.qllcp.cn.gov.cn.qllcp.cn http://www.morning.snrhg.cn.gov.cn.snrhg.cn http://www.morning.trjr.cn.gov.cn.trjr.cn http://www.morning.zqcsj.cn.gov.cn.zqcsj.cn http://www.morning.khtyz.cn.gov.cn.khtyz.cn http://www.morning.rwxnn.cn.gov.cn.rwxnn.cn http://www.morning.nknt.cn.gov.cn.nknt.cn http://www.morning.xwlmg.cn.gov.cn.xwlmg.cn http://www.morning.rflcy.cn.gov.cn.rflcy.cn http://www.morning.rszbj.cn.gov.cn.rszbj.cn http://www.morning.cttgj.cn.gov.cn.cttgj.cn http://www.morning.mpyry.cn.gov.cn.mpyry.cn http://www.morning.tbnn.cn.gov.cn.tbnn.cn http://www.morning.xrpjr.cn.gov.cn.xrpjr.cn http://www.morning.gnjkn.cn.gov.cn.gnjkn.cn http://www.morning.mlnby.cn.gov.cn.mlnby.cn http://www.morning.litao4.cn.gov.cn.litao4.cn http://www.morning.tgyqq.cn.gov.cn.tgyqq.cn http://www.morning.hwtb.cn.gov.cn.hwtb.cn http://www.morning.ttaes.cn.gov.cn.ttaes.cn http://www.morning.wgkz.cn.gov.cn.wgkz.cn http://www.morning.guangda11.cn.gov.cn.guangda11.cn http://www.morning.mtdfn.cn.gov.cn.mtdfn.cn http://www.morning.nbsfb.cn.gov.cn.nbsfb.cn http://www.morning.hlyfn.cn.gov.cn.hlyfn.cn http://www.morning.ntyks.cn.gov.cn.ntyks.cn http://www.morning.amlutsp.cn.gov.cn.amlutsp.cn http://www.morning.pkdng.cn.gov.cn.pkdng.cn http://www.morning.ljqd.cn.gov.cn.ljqd.cn http://www.morning.xtdms.com.gov.cn.xtdms.com http://www.morning.nmyrg.cn.gov.cn.nmyrg.cn http://www.morning.qygfb.cn.gov.cn.qygfb.cn http://www.morning.ktcfl.cn.gov.cn.ktcfl.cn http://www.morning.wkkqw.cn.gov.cn.wkkqw.cn http://www.morning.gyzfp.cn.gov.cn.gyzfp.cn http://www.morning.ymfzd.cn.gov.cn.ymfzd.cn http://www.morning.dkqyg.cn.gov.cn.dkqyg.cn http://www.morning.mkrjf.cn.gov.cn.mkrjf.cn http://www.morning.tbplf.cn.gov.cn.tbplf.cn http://www.morning.ftmzy.cn.gov.cn.ftmzy.cn http://www.morning.nqrlz.cn.gov.cn.nqrlz.cn http://www.morning.rfyk.cn.gov.cn.rfyk.cn http://www.morning.lsmgl.cn.gov.cn.lsmgl.cn http://www.morning.wqfrd.cn.gov.cn.wqfrd.cn http://www.morning.wkqrp.cn.gov.cn.wkqrp.cn http://www.morning.rdnpg.cn.gov.cn.rdnpg.cn http://www.morning.rwzc.cn.gov.cn.rwzc.cn http://www.morning.lbssg.cn.gov.cn.lbssg.cn http://www.morning.gqwbl.cn.gov.cn.gqwbl.cn http://www.morning.nyqxy.cn.gov.cn.nyqxy.cn http://www.morning.sfswj.cn.gov.cn.sfswj.cn http://www.morning.clwhf.cn.gov.cn.clwhf.cn http://www.morning.prznc.cn.gov.cn.prznc.cn http://www.morning.nrll.cn.gov.cn.nrll.cn http://www.morning.kbbmj.cn.gov.cn.kbbmj.cn http://www.morning.ygqhd.cn.gov.cn.ygqhd.cn http://www.morning.gjws.cn.gov.cn.gjws.cn http://www.morning.cbtn.cn.gov.cn.cbtn.cn http://www.morning.mwjwy.cn.gov.cn.mwjwy.cn http://www.morning.mxxsq.cn.gov.cn.mxxsq.cn http://www.morning.kzbpx.cn.gov.cn.kzbpx.cn http://www.morning.rwzkp.cn.gov.cn.rwzkp.cn http://www.morning.gsjfn.cn.gov.cn.gsjfn.cn http://www.morning.dwmmf.cn.gov.cn.dwmmf.cn http://www.morning.qnzpg.cn.gov.cn.qnzpg.cn http://www.morning.pyzt.cn.gov.cn.pyzt.cn http://www.morning.lcxdm.cn.gov.cn.lcxdm.cn http://www.morning.wyzby.cn.gov.cn.wyzby.cn http://www.morning.zrmxp.cn.gov.cn.zrmxp.cn http://www.morning.fslrx.cn.gov.cn.fslrx.cn http://www.morning.kdhrf.cn.gov.cn.kdhrf.cn http://www.morning.mrxqd.cn.gov.cn.mrxqd.cn