温馨提示×

java怎么调用rest接口

小亿
118
2023-11-13 23:08:07
栏目: 编程语言

在Java中调用REST接口,通常需要使用Java的HTTP客户端库来发送HTTP请求并接收响应。以下是使用Java的HttpURLConnection类来调用REST接口的示例代码:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class RESTClient {
    public static void main(String[] args) {
        try {
            // 创建URL对象
            URL url = new URL("http://api.example.com/restEndpoint");

            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法
            connection.setRequestMethod("GET");

            // 添加请求头(可根据需要设置)
            connection.setRequestProperty("User-Agent", "Java REST Client");

            // 获取响应代码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
            reader.close();

            // 输出响应内容
            System.out.println("Response Body: " + response.toString());

            // 断开连接
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在上述示例中,我们使用了Java的HttpURLConnection类来发送HTTP GET请求。可以根据需要更改请求方法(如POST、PUT、DELETE等),并根据需要设置请求头。在获取响应后,可以通过读取输入流来获取响应内容。

注意:上述示例仅为基本示例,实际应用中可能需要处理更多的请求参数、请求体和响应内容。可以根据具体需求来扩展和改进代码。

0