Author Topic: [Java Snippets] Using proxies  (Read 4607 times)

0 Members and 1 Guest are viewing this topic.

Offline Deque

  • P.I.N.N.
  • Global Moderator
  • Overlord
  • *
  • Posts: 1203
  • Cookies: 518
  • Programmer, Malware Analyst
    • View Profile
[Java Snippets] Using proxies
« on: January 07, 2013, 08:03:03 pm »
Hi EZ,

these snippets show how to use proxies in Java.

ProxyHelper loads a proxylist of the format address:port:type (one proxy per line) and returns a proxy, if requested.

Code: (Java) [Select]
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.SocketAddress;
import java.util.LinkedList;
import java.util.Random;

public class ProxyHelper {

    private final Random rand;
    private final LinkedList<Proxy> proxies = new LinkedList<Proxy>();

    public ProxyHelper(String filename) {
        rand = new Random();
        loadProxies(filename);
    }

    public Proxy getAndRemoveRandomProxy() {
        int num = rand.nextInt(proxies.size());
        System.out.println(proxies.size());
        Proxy proxy = proxies.remove(num);
        System.out.println(proxy.address());
        return proxy;
    }

    // file format: "address:port:type"
    private void loadProxies(String filename) {
        try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = br.readLine()) != null) {
                String[] data = line.split(":");
                SocketAddress address = new InetSocketAddress(data[0],
                        Integer.parseInt(data[1]));
                Proxy.Type type = Proxy.Type.valueOf(data[2]);
                proxies.add(new Proxy(type, address));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This is how you actually use the proxy:

Code: (Java) [Select]
Proxy proxy = proxyHelper.getAndRemoveRandomProxy();
URL url = new URL("http://evilzone.org");
URLConnection urlc = url.openConnection(proxy);
BufferedReader reader = new BufferedReader(new
                        InputStreamReader(urlc.getInputStream()));
« Last Edit: January 07, 2013, 08:03:34 pm by Deque »