java如何调用接口
调用接口的基本方法
在Java中调用接口通常涉及实现接口或使用接口引用对象。以下是几种常见场景的示例:
定义接口
public interface MyInterface {
void doSomething();
}
实现接口
public class MyClass implements MyInterface {
@Override
public void doSomething() {
System.out.println("Doing something...");
}
}
通过接口引用调用

MyInterface obj = new MyClass();
obj.doSomething();
调用REST API接口
对于HTTP接口调用,常用HttpURLConnection或第三方库如OkHttp/Apache HttpClient:
使用HttpURLConnection

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.toString());
}
使用Spring RestTemplate
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("https://api.example.com/data", String.class);
调用WebService接口
使用JAX-WS生成客户端代码:
URL wsdlUrl = new URL("http://example.com/service?wsdl");
QName qname = new QName("http://example.com/", "MyService");
Service service = Service.create(wsdlUrl, qname);
MyInterface port = service.getPort(MyInterface.class);
port.doSomething();
异步接口调用
使用CompletableFuture实现异步调用:
CompletableFuture.supplyAsync(() -> {
// 模拟耗时操作
try { Thread.sleep(1000); }
catch (InterruptedException e) { e.printStackTrace(); }
return "Result";
}).thenAccept(result -> System.out.println("Got: " + result));
注意事项
- 实现接口时必须实现所有抽象方法
- HTTP调用需处理异常和关闭连接
- WebService调用需要正确配置WSDL地址
- 生产环境建议使用连接池管理HTTP连接
- 考虑添加超时和重试机制






