通过java中的代理服务器连接到网站

时间:2012-10-15 15:52:19

标签: java proxy urlconnection

我在浏览器上通过代理显示网站时遇到问题。我将我的代理从Internet选项手动设置为127.0.0.1:80。在我连接到网站的代码中,我可以获取html代码并将其打印在我的java控制台上。但是,当我将html代码发送到我的浏览器时,我可以看到它连接到网站并显示标题为“欢迎使用Facebook”。但我看不到内容。有时我只看到作品而不是图像或其他东西。显示网页内容存在问题。我无法理解。也许你可以帮助我。另外我想我无法获得UTF-8格式的内容。谢谢。

      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);
                    }

这是我向浏览器发送行的方式。

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

1 个答案:

答案 0 :(得分:1)

您可以在URL连接之前通过System.setProperty()在java中设置代理。

对于http连接 -

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

对于https连接 -

System.setProperty("https.proxyHost", " 127.0.0.1");
System.setPropery("https.proxyPort", "80");
相关问题