如何通过HTTP代理连接Socket服务器 [英] How to connect a Socket server via HTTP proxy

查看:112
本文介绍了如何通过HTTP代理连接Socket服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码连接到Socket服务器,它工作正常。

I have a piece of code to connect to a Socket server, and it works fine.

Socket socket = new Socket();
socket.connect(new InetSocketAddress(address, port));

现在我想通过HTTP代理连接,我该怎么办?

Now I want to connect via a HTTP proxy, what should I do?

我试过这个并且失败了

SocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
Socket socket = new Socket(proxy);
socket.connect(new InetSocketAddress(address, port));

这篇文章建议我应该使用 Jakarta Commons HttpClient ,但如何使用它通过HTTP代理连接Socket服务器?

this post suggests that I should use Jakarta Commons HttpClient, but how to use it to connect a Socket server via the HTTP proxy?

更新:
我使用SOCKS代理,如果我使用HTTP代理它不起作用:

UPDATED: I used SOCKS proxy and it doesn't work, if I use HTTP proxy:

SocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
Socket socket = new Socket(proxy);
socket.connect(new InetSocketAddress(address, port));

它将抛出IllegalArgumentException

and it will throw an IllegalArgumentException

java.lang.IllegalArgumentException: Proxy is null or invalid type
    at java.net.Socket.<init>(Socket.java:88)


推荐答案

这是我之前发布的链接:

This is from the link I posted previously:

SocketAddress addr = new InetSocketAddress("webcache.mydomain.com", 8080);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);

请记住,这个新的代理对象代表了一个代理定义,仅此而已。我们如何使用这样的对象?新的 openConnection()方法已添加到URL类中,并将Proxy作为参数,它的工作方式与 openConnection()的工作方式相同/ code>没有参数,除了它强制通过指定的代理建立连接,忽略所有其他设置,包括上面提到的系统属性。

Remember, this new proxy object represents a proxy definition, nothing more. How do we use such an object? A new openConnection() method has been added to the URL class and takes a Proxy as an argument, it works the same way as openConnection() with no arguments, except it forces the connection to be established through the specified proxy, ignoring all other settings, including the system properties mentioned above.

完成上一个示例后,我们现在可以添加:

So completing the previous example, we can now add:

URL url = new URL("http://java.sun.com/");
URLConnection conn = url.openConnection(proxy);

这是我之前发布的链接。我在iPad上,所以无法正确格式化。

This is from the link I posted earlier. I'm on the iPad so can't format it properly.

你能这样做吗?我看到你正在直接进行套接字,但你正在做http,所以也许这样做?

Can you do it this way? I see you're doing sockets directly but you're doing http so maybe do things this way?

这篇关于如何通过HTTP代理连接Socket服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆