共计 1900 个字符,预计需要花费 5 分钟才能阅读完成。
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。
丸趣 TV 网 – 提供最优质的资源集合!
正文完