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

java如何调用rest api接口

java如何调用rest api接口

在Java中调用REST API接口,通常有以下几种方法: 1. 使用原生的HttpURLConnection类```javaimport java.io.Buffer...

在Java中调用REST API接口,通常有以下几种方法:

1. 使用原生的HttpURLConnection类

```java

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

public class RestApiExample {

public static void main(String[] args) {

try {

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

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

最新文章