1111111

该篇文章介绍了如何在Java中使用HttpClient,通过指定本地IP地址并发送HTTPGET请求到www.example.com。代码展示了创建Socket连接,发送请求头,接收响应并处理异常的过程。
摘要由CSDN通过智能技术生成
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();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值