有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我无法通过代理在浏览器上显示网站。我手动将代理从Internet选项设置为127.0.0.1:80。在连接到web站点的代码中,我可以获取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) 个答案

  1. # 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");