java url中域名 请求时指定ip
在Java中,可以使用URLConnection或HttpURLConnection类来发送HTTP请求。以下是一个示例代码,演示如何在URL中指定IP地址发送请求:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Main {
public static void main(String[] args) throws IOException {
String ipAddress = "192.168.0.1"; // IP地址
String urlString = "http://" + ipAddress + "/api/endpoint"; // URL地址
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
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: " + response.toString());
connection.disconnect();
}
}
在上面的示例中,我们创建了一个URL对象,并使用指定的IP地址和端点构建了完整的URL字符串。然后,我们使用openConnection()方法打开与该URL的连接,并将其转换为HttpURLConnection类型。接下来,我们可以设置请求方法(例如GET、POST等)和其他请求头信息。最后,我们可以通过getResponseCode()方法获取响应代码,并通过getInputStream()方法获取响应的输入流来读取响应数据。
请注意,这只是发送请求时指定IP地址的一种方法。实际上,可以根据具体的需求选择不同的方法和类来发送HTTP请求。此外,还可以使用第三方库,如Apache HttpClient或OkHttp,来更方便地处理HTTP请求
原文地址: http://www.cveoy.top/t/topic/iJq2 著作权归作者所有。请勿转载和采集!