云服务器免费试用

java如何调用restful接口

服务器知识 0 1261

Java可以使用HttpURLConnection或者HttpClient来调用RESTful接口。
使用HttpURLConnection调用RESTful接口的示例代码如下:
```java
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接口的示例代码如下:
```java
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。

java如何调用restful接口

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942@qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: java如何调用restful接口
本文地址: https://solustack.com/58392.html

相关推荐:

网友留言:

我要评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。