溫馨提示×

java如何調(diào)用restful接口

小億
249
2023-09-13 11:46:42
欄目: 編程語言

Java可以使用HttpURLConnection或者HttpClient來調(diào)用RESTful接口。

使用HttpURLConnection調(diào)用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 {
// 創(chuàng)建URL對象
URL url = new URL("http://api.example.com/resource");
// 創(chuàng)建HttpURLConnection對象
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設(shè)置請求方法為GET
connection.setRequestMethod("GET");
// 發(fā)送請求并獲取響應(yīng)狀態(tài)碼
int responseCode = connection.getResponseCode();
// 根據(jù)響應(yīng)狀態(tài)碼判斷請求是否成功
if (responseCode == HttpURLConnection.HTTP_OK) {
// 讀取響應(yīng)內(nèi)容
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// 打印響應(yīng)內(nèi)容
System.out.println(response.toString());
} else {
System.out.println("請求失敗,狀態(tài)碼:" + responseCode);
}
// 關(guān)閉連接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
}
}

使用HttpClient調(diào)用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 {
// 創(chuàng)建HttpGet對象
HttpGet httpGet = new HttpGet("http://api.example.com/resource");
// 發(fā)送請求并獲取響應(yīng)
CloseableHttpResponse response = httpClient.execute(httpGet);
// 獲取響應(yīng)內(nèi)容
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity);
// 打印響應(yīng)內(nèi)容
System.out.println(responseString);
// 關(guān)閉響應(yīng)
response.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// 關(guān)閉HttpClient連接
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

以上代碼示例中的URL為示例地址,需要根據(jù)實(shí)際情況替換成要調(diào)用的RESTful接口的URL。

0