JavaでRESTfulインターフェースを呼び出す
Javaでは、RESTfulインターフェイスを呼び出すためにHttpURLConnectionまたはHttpClientを使用できます。
以下に、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();
}
}
}
RESTful APIを呼び出すためのHttpClientを使用したサンプルコードを以下に示します。
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に置き換えてください。