当前位置:首页 > 编程技术 > 正文

java web如何调用接口

java web如何调用接口

在Java Web中调用接口主要有以下几种方式: 1. 使用`HttpURLConnection`Java内置的`HttpURLConnection`类可以用来发送HT...

在Java Web中调用接口主要有以下几种方式:

1. 使用`HttpURLConnection`

Java内置的`HttpURLConnection`类可以用来发送HTTP请求。

```java

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) {

try {

URL url = new URL("http://example.com/api/data");

HttpURLConnection connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod("GET");

int responseCode = connection.getResponseCode();

System.out.println("Response Code: " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String inputLine;

StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {

response.append(inputLine);

最新文章