import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
public class HttpClientWithCustomLocalIP {
public static void main(String[] args) {
try {
// 指定要使用的本地IP地址
InetAddress localIpAddress = InetAddress.getByName("your_desired_ip");
// 创建Socket并绑定到指定的本地IP地址
Socket socket = new Socket(localIpAddress, 80); // 这里的80是目标服务器的端口号
// 发送HTTP GET请求
OutputStream out = socket.getOutputStream();
out.write("GET / HTTP/1.1\r\n".getBytes());
out.write("Host: www.example.com\r\n".getBytes());
out.write("\r\n".getBytes());
// 读取响应
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
// 关闭Socket
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
1111111
最新推荐文章于 2024-09-25 11:06:23 发布
该篇文章介绍了如何在Java中使用HttpClient,通过指定本地IP地址并发送HTTPGET请求到www.example.com。代码展示了创建Socket连接,发送请求头,接收响应并处理异常的过程。
摘要由CSDN通过智能技术生成