Government Security
Network Security Resources

Jump to content

Photo

Java Http Connection Through A Proxy

- - - - - proxy java
  • Please log in to reply
No replies to this topic

#1 Juza

Juza

    Specialist

  • Sergeant Major
  • 149 posts

Posted 15 October 2010 - 08:51 AM

Hello people!

I had a problem when i was programing a http client and i want to add proxy support to it.
I was googling and a i found the Proxy class witch I thought at the time that will solve my problem, but was very much mistaken.

The code was like this:

Socket s = new Socket(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy", 3128)));
try {
    s.connect(new InetSocketAddress("www.google.com", 80));
} catch (IOException ex) {
    ex.printStackTrace();
}


Everything well coded, and ... "Invalid proxy!".
I had tried several times in various ways but nothing!

So if you have this problem, this is the solution!
You only have to connect directly to the proxy and do the requests for it.

Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;

try {
    socket = new Socket("proxy", 3128);
} catch (UnknownHostException ex) {
    System.out.println("Can't resolve the host!");
} catch (IOException ex) {
    System.out.println("Can't connect to the host!");
}

try {
    out = new PrintWriter(socket.getOutputStream(), true);
    in = new BufferedReader(new InputStreamReader(
            socket.getInputStream()));
} catch (IOException ex) {
    ex.printStackTrace();
}

out.println("GET http://www.google.com HTTP/1.0\n\n");

String inStr;
try {
    while ((inStr = in.readLine()) != null) {
        System.out.println(inStr);
    }
    in.close();
} catch (IOException ex) {
    ex.printStackTrace();
}

So this is it!

I hope you have learn something!

Juza
Go to iamjuza.blogspot.com
Follow me twitter.com/iamjuza

The true beginning of our end.






Also tagged with one or more of these keywords: proxy, java