温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何在Java中使用HTTP代理

发布时间:2025-11-19 19:36:47 来源:亿速云 阅读:109 作者:小樊 栏目:编程语言

在Java中,您可以使用java.net.Proxyjava.net.URLConnection类来通过HTTP代理访问网络资源。以下是一个简单的示例,展示了如何使用HTTP代理连接到URL:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

public class HttpProxyExample {

    public static void main(String[] args) {
        try {
            // 设置代理服务器的地址和端口
            String proxyHost = "proxy.example.com";
            int proxyPort = 8080;

            // 创建一个代理对象
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));

            // 设置要访问的URL
            URL url = new URL("http://example.com");

            // 打开连接并设置代理
            HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);

            // 设置请求方法(GET、POST等)
            connection.setRequestMethod("GET");

            // 获取响应码
            int responseCode = connection.getResponseCode();
            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();

            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }

            // 关闭输入流
            in.close();

            // 打印响应内容
            System.out.println("Response Content: " + content.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们首先设置了代理服务器的地址和端口。然后,我们创建了一个Proxy对象,并将其传递给url.openConnection(proxy)方法。这将使连接通过指定的HTTP代理进行。

请注意,您需要根据实际情况替换代理服务器地址、端口和要访问的URL。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI