class Main{
//we can use class HttpClient
//https://www.youtube.com/watch?v=5MmlRZZxTqk
public static void main(String args[]) throws IOException, InterruptedException {
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
// .GET() this line is optional because it is default
.header("accept","application/json")
.uri(URI.create("https://whatever.com"))
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.statusCode());
System.out.println(response.body());
System.out.println(response.getClass().getName());
}
}
所以我阅读了关于BodyHandlers.ofString()方法的文档,我的理解是它将解析响应变量的值为字符串。但如果是这样,为什么当我输入
这行System.out.println(response.getClass().getName());
结果是jdk.internal.net.http.HttpResponseImpl?我读到另一篇文章说你不应该在idk.internal.*中使用任何类,所以我做错了什么吗?
我做错了什么吗?
这里没有问题,HttpResponse
是接口。因此,response.getClass()
可以返回任何实现HttpResponse
(在本例中为HttpResponseImpl
)的实现。
我看到另一篇文章说你不应该在idk.internal.*中使用任何类
这意味着你不应该在代码中直接声明/初始化这个类。例如,你不应该这样写:
HttpResponseImpl<String> response;
背后的原则是我们应该依赖接口,而不是实现细节,更多细节可以在JEP 260
中找到。