API调用困惑:如何使用Java HTTP客户端正确访问RESTful服务?
在Java中,我们可以使用HttpURLConnection或者更现代的如Apache HttpClient和OkHttp等库来访问RESTful服务。
以下是一个基本的例子,展示了如何使用HttpURLConnection来访问一个GET请求的RESTful服务:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import javax.net.ssl.HttpsURLConnection;
public class RESTClient {
public static void main(String[] args) {
String url = "https://example.com/api/resource"; // RESTful服务URL
try (HttpURLConnection conn = new HttpsURLConnection(url)) {
conn.setRequestMethod("GET"); // 发送GET请求
conn.setConnectTimeout(1000); // 设置连接超时时间
if (conn.getResponseCode() == 200) { // 如果响应状态码为200(表示成功),
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()))); // 创建BufferedReader读取响应内容
String responseContent = br.readLine(); // 读取第一行内容(通常为JSON格式)
System.out.println("Response Content: " + responseContent); // 打印响应内容
} else {
System.out.println("Failed to fetch data. Response Code: " + conn.getResponseCode()); // 如果请求失败,打印错误信息
}
} catch (Exception e) {
System.err.println("Error occurred while fetching data: " + e.getMessage());
e.printStackTrace();
}
}
}
请确保你的RESTful服务端允许GET请求,并且返回内容格式为JSON。
还没有评论,来说两句吧...