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。