Java

java如何调用restful接口

小亿
267
2023-09-13 11:46:42
栏目: 编程语言

Java可以使用HttpURLConnection或者HttpClient来调用RESTful接口。

使用HttpURLConnection调用RESTful接口的示例代码如下:

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/resource");
// 创建HttpURLConnection对象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 设置请求方法为GET
connection.setRequestMethod("GET");
// 发送请求并获取响应状态码
int responseCode = connection.getResponseCode();
// 根据响应状态码判断请求是否成功
if (responseCode == HttpURLConnection.HTTP_OK) {
// 读取响应内容
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.toString());
} else {
System.out.println("请求失败,状态码:" + responseCode);
}
// 关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}

使用HttpClient调用RESTful接口的示例代码如下:

import org.apache.http.HttpEntity;
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;
import org.apache.http.util.EntityUtils;
public class RestClient {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 创建HttpGet对象
HttpGet httpGet = new HttpGet("http://api.example.com/resource");
// 发送请求并获取响应
CloseableHttpResponse response = httpClient.execute(httpGet);
// 获取响应内容
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
// 打印响应内容
System.out.println(responseString);
// 关闭响应
response.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 关闭HttpClient连接
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

以上代码示例中的URL为示例地址,需要根据实际情况替换成要调用的RESTful接口的URL。

0
看了该问题的人还看了