java如何调用restful接口

   2025-02-22 6660
核心提示:Java可以使用HttpURLConnection或者HttpClient来调用RESTful接口。使用HttpURLConnection调用RESTful接口的示例代码如下:import

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();// 设置请求方法为GETconnection.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。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言