如何在 Java 中使用 HTTP GET 请求?

问题描述

我正在尝试将现有的 Python 脚本重新编码为 Java。 它包括以下行:

r = requests.get('https://{}/redfish/v1/{}'.format(ip,query),auth=('ADMIN','ADMIN'),verify=False)

我在 Python 方面没有很多经验,也没有自己编写脚本。到目前为止,我只能弄清楚它的作用,但不知道如何使用 Java 复制它。

如果有人能指出我正确的方向,那就太棒了。

谢谢!

解决方法

首先,阅读this tutorial on the java HTTP client。 (注意需要jdk11以上)

从那里开始它应该相当简单; .format() 只是用提供的 ip 和查询部分替换 {}。身份验证部分更有趣。验证部分大概意味着“无论如何,忘记 SSL”。

在 'admin' 和 'disregard SSL issues' 之间的密码,这段代码尖叫着“你距离你的盒子 p0wned 大约还有 2 周的时间”,也许你应该比这更认真地对待安全。

无论如何,java 领域的等价物更复杂,因为 java 有意并不意味着“禁用 ssl”是一个随意的一次性举动,不像 python 只是给你火箭筒而不问任何问题。

Here is a tutorial on how to do basic http auth with the http client

为了正确地射击你的脚并确保你的脚完全死了,你需要创建一个不做任何事情并且默默地接受所有证书的 SSL 上下文,即使是那些试图破解你的系统的人。然后将 .sslContext 的值传递给 HttpClient.builder()

Here is an example of someone firing this bazooka

,

首先,您可以使用 String.format 进行格式化:

String url=String.format("https://%s/redfish/v1/%s",ip,query);

如果需要,您也可以使用 MessageFormat

对于连接,您可以创建一个 URL 对象并创建一个 URLConnection(在您的情况下为 HttpsURLConnection),然后为响应打开一个 InputStream:>

HttpsURLConnectioncon=(HttpsURLConnection)new URL(url).openConnection();
try(BufferedInputStream is=new BufferedInputStream(con.openStream()){
    //...
}

为了进行身份验证,您可以查看this tutorial

String auth =  "ADMIN:ADMIN";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
//Get the HttpURLConnection
con.setRequestProperty("Authorization",authHeaderValue);
//Connect/open InputStream

如果您真的想禁用验证,您可以创建自己的 HostnameVerifier 以允许所有内容,但强烈建议不要这样做,因为这允许中间人攻击,就像您基本上禁用 HTTPs 的安全性

con.setHostnameVerifier((hostname,sslSession)->true);

综合起来,它可能是这样的:

String url=String.format("https://%s/redfish/v1/%s",query);

String auth =  "ADMIN:ADMIN";
byte[] encodedAuth = Base64.getEncoder().encode(auth.getBytes(StandardCharsets.UTF_8));
String authHeaderValue = "Basic " + new String(encodedAuth);

HttpsURLConnection con=(HttpsURLConnection)new URL(url).openConnection();

con.setRequestProperty("Authorization",authHeaderValue);
con.setHostnameVerifier((hostname,sslSession)->true);//vulnerable to man in the middle attacks

try(BufferedInputStream is=new BufferedInputStream(con.openStream()){
    //...
}