Ahmet Tanakol
Ahmet Tanakol

Reputation: 899

Urlconnection to a web site via proxy server in java

I have a problem in displaying web sites on my browser via proxy. I set my proxy manually from Internet Options to 127.0.0.1:80. In the code when I make a connection to web site, I can get the html code and print it on my java console. However, when I send the html code to my browser, I can see that it connects to web site and shows the title like "Welcome to Facebook". But I cannot see the content. Sometimes I see only writings not images or other things. There is a problem about displaying the web page content. I couldn't figure it out. Maybe you can help me. Also I think I can't get the content in UTF-8 format. Thank you.

      try {
                        URL url = new URL("" + req.url);
                        URLConnection urlConnection = url.openConnection();
                        DataInputStream dis = new DataInputStream(urlConnection.getInputStream());
                        String inputLine;

                        while ((inputLine =  dis.readLine()) != null) {
                         //   System.out.println(inputLine);
                            out.writeUTF(inputLine);

                        }
                        dis.close();
                    } catch (MalformedURLException me) {
                        System.out.println("MalformedURLException: " + me);
                    } catch (IOException ioe) {
                        System.out.println("IOException: " + ioe);
                    }

This is how I send lines to browser.

private DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());

Upvotes: 0

Views: 716

Answers (1)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

You can set proxy in java by System.setProperty() before URL Connection.

For http connection -

System.setProperty("http.proxyHost", " 127.0.0.1");
System.setPropery("http.proxyPort", "80");

For https connection -

System.setProperty("https.proxyHost", " 127.0.0.1");
System.setPropery("https.proxyPort", "80");

Upvotes: 1

Related Questions