java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java对接第三方接口

java对接第三方接口的三种实现方式

作者:酷爱码

这篇文章主要为大家详细介绍了java对接第三方接口的三种实现方式,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以参考一下

方式一:同步HTTP调用

实现原理

通过阻塞式HTTP请求直接获取响应结果,适用于实时性要求高的场景。

代码示例(使用HttpClient)

// 创建HTTP客户端
CloseableHttpClient client = HttpClients.createDefault();

// 构建GET请求
HttpGet request = new HttpGet("https://api.example.com/data?param=value");
request.setHeader("Content-Type", "application/json");

// 执行请求并处理响应
try (CloseableHttpResponse response = client.execute(request)) {
    String result = EntityUtils.toString(response.getEntity());
    System.out.println("响应结果:" + result);
} catch (IOException e) {
    e.printStackTrace();
}

关键点

方式二:异步回调模式

实现原理

代码结构

// 创建HTTP客户端
CloseableHttpClient client = HttpClients.createDefault();

// 构建GET请求
HttpGet request = new HttpGet("https://api.example.com/data?param=value");
request.setHeader("Content-Type", "application/json");

// 执行请求并处理响应
try (CloseableHttpResponse response = client.execute(request)) {
    String result = EntityUtils.toString(response.getEntity());
    System.out.println("响应结果:" + result);
} catch (IOException e) {
    e.printStackTrace();
}

注意事项

方式三:消息队列中间件

实现原理

通过消息队列实现解耦,适用于高并发场景。

RabbitMQ实现示例

// 消息生产者
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("localhost");
try (Connection connection = factory.newConnection();
     Channel channel = connection.createChannel()) {
    channel.queueDeclare("API_QUEUE", true, false, false, null);
    channel.basicPublish("", "API_QUEUE", null, message.getBytes());
}

// 消息消费者
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
    String message = new String(delivery.getBody(), "UTF-8");
    // 调用第三方接口
    callThirdPartyAPI(message);
};
channel.basicConsume("API_QUEUE", true, deliverCallback, consumerTag -> {});

优势分析

对比总结

对比维度同步调用异步回调消息队列
响应时效实时(毫秒级)延迟(秒级)可变
系统耦合度
吞吐量低(受限于连接数)
实现复杂度简单中等较高

选型建议

通用注意事项

使用HTTPS保证传输安全

添加请求签名防止篡改

记录完整日志(建议包含请求/响应报文)

实现熔断机制(如Hystrix)

配置监控报警(超时率/错误率)

方法补充

1. 使用 HttpURLConnection(JDK原生)

Java标准库提供的底层HTTP客户端,适合简单的请求,无需第三方依赖。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
 
public class HttpUrlConnectionExample {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://api.example.com/data");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        
        int responseCode = conn.getResponseCode();
        if (responseCode == 200) {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println(response);
        }
    }
}

特点:

优点:无需第三方依赖。

缺点:代码冗余,需手动处理输入输出流、状态码等。

2. 使用 Apache HttpClient

Apache提供的功能强大的HTTP客户端库,支持连接池、重试、认证等高级功能。

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;
 
public class ApacheHttpClientExample {
    public static void main(String[] args) throws Exception {
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet request = new HttpGet("https://api.example.com/data");
            try (CloseableHttpResponse response = client.execute(request)) {
                System.out.println(response.getStatusLine().getStatusCode());
                // 处理响应内容...
            }
        }
    }
}

特点:

优点:功能全面,社区支持好。

缺点:需引入org.apache.httpcomponents:httpclient依赖。

3. 使用 Spring RestTemplate 或 WebClient

适用于Spring项目,简化REST API调用。

RestTemplate(同步)

import org.springframework.web.client.RestTemplate;
 
public class RestTemplateExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.example.com/data";
        String response = restTemplate.getForObject(url, String.class);
        System.out.println(response);
    }
}

WebClient(异步,响应式)

import org.springframework.web.reactive.function.client.WebClient;
 
public class WebClientExample {
    public static void main(String[] args) {
        WebClient webClient = WebClient.create("https://api.example.com");
        String response = webClient.get()
                .uri("/data")
                .retrieve()
                .bodyToMono(String.class)
                .block(); // 同步阻塞获取结果
        System.out.println(response);
    }
}

特点:

优点:与Spring生态集成,支持JSON序列化、异常处理。

缺点:需引入Spring框架依赖(如spring-boot-starter-web或spring-boot-starter-webflux)。

4. 使用 OkHttp

Square公司开发的高效HTTP客户端,适合移动端或轻量级应用。

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
 
public class OkHttpExample {
    public static void main(String[] args) throws Exception {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("https://api.example.com/data")
                .build();
        try (Response response = client.newCall(request).execute()) {
            System.out.println(response.body().string());
        }
    }
}

特点:

优点:轻量高效,支持HTTP/2。

缺点:需引入com.squareup.okhttp3:okhttp依赖。

5. 使用 Feign Client(声明式HTTP客户端)

适用于微服务架构,通过接口和注解定义HTTP请求。

// 定义Feign接口
@FeignClient(name = "exampleClient", url = "https://api.example.com")
public interface ExampleClient {
    @GetMapping("/data")
    String getData();
}
 
// 使用示例(需结合Spring Cloud)
@SpringBootApplication
@EnableFeignClients
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

特点:

优点:代码简洁,支持负载均衡(结合Ribbon)。

缺点:需依赖Spring Cloud生态。

6. 使用 JAX-RS Client(Jersey或RESTEasy)

基于JAX-RS标准的客户端,适合JAX-RS兼容的API。

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.Response;
 
public class JaxRsClientExample {
    public static void main(String[] args) {
        Client client = ClientBuilder.newClient();
        Response response = client.target("https://api.example.com/data")
                .request()
                .get();
        System.out.println(response.readEntity(String.class));
    }
}

特点:

优点:标准化,支持RESTful语义。

缺点:需引入JAX-RS实现库(如org.glassfish.jersey.core:jersey-client)。

7. 使用第三方工具(如Unirest)

简化HTTP调用的工具库,语法简洁。

import kong.unirest.Unirest;
 
public class UnirestExample {
    public static void main(String[] args) {
        String response = Unirest.get("https://api.example.com/data")
                .asString()
                .getBody();
        System.out.println(response);
    }
}

特点:

优点:API简洁,适合快速开发。

缺点:需引入com.konghq:unirest-java依赖。

8. 使用WebService客户端(如JAX-WS或Apache CXF)

针对SOAP协议的WebService接口调用。

// JAX-WS示例
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import java.net.URL;
 
public class JaxWsExample {
    public static void main(String[] args) throws Exception {
        URL wsdlUrl = new URL("http://example.com/service?wsdl");
        QName qname = new QName("http://example.com/", "ExampleService");
        Service service = Service.create(wsdlUrl, qname);
        ExampleService port = service.getPort(ExampleService.class);
        String result = port.getData();
        System.out.println(result);
    }
}

特点:

优点:适合SOAP协议。

缺点:代码复杂,需生成客户端存根。

选择建议

简单请求:优先使用HttpURLConnection或OkHttp。

Spring项目:使用RestTemplate(传统同步)或WebClient(响应式异步)。

微服务架构:使用Feign Client。

高性能需求:选择OkHttp或Apache HttpClient。

SOAP协议:使用JAX-WS或Apache CXF。

到此这篇关于java对接第三方接口的三种实现方式的文章就介绍到这了,更多相关java对接第三方接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文