Java socket – use proxy server

There's no need to say more about why you use a proxy server.

Using proxy

Java provides a proxy class implementation that uses a proxy to communicate.

The constructor of proxy class (proxy. Type, socketaddress SA). Type represents the proxy type. There are three Proxy types: direct (indicating no proxy), HTTP (indicating advanced protocol proxy, such as HTTP or FTP), socks (indicating sockets proxy). SA represents the proxy address.

Once the proxy object is created, the program can pass in a proxy object as the proxy server for this connection when opening a connection with urlconnection or creating a connection with socket.

The URL provides a urlconnection openconnection (proxy proxy); Socket provides a socket (proxy) constructor.

Take openconnection of URL as an example:

Using proxyselector

Without further explanation, go directly to the code:

The above code does not explicitly specify a proxy server, but when I provide an invalid proxy IP, the console outputs the words "connection proxy failed". Explain that the program uses the agent I provided.

Proxyselector is an abstract class. It provides two methods, select and connectfailed, which need to be implemented by the user:

Java provides an implementation class defaultproxyselector for proxyselector and registers it as the default proxy implementation class. Generally, it does not need to be explicitly implemented. If necessary, you can use proxyselector Getdefault(). Briefly describe the implementation of proxyselector by defaultproxyselector:

The following is an example (I didn't bother to write it myself, so I directly found one on the Internet):

This is well written.

That's it.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>