【问题标题】:google search and print result in java谷歌搜索并在java中打印结果
【发布时间】:2018-07-06 20:15:19
【问题描述】:

在这里,我希望在 Google 上执行搜索,并使用终端将结果作为单独的输出文件获取。在终端中,只会输入要搜索的关键字。这就是我所做的。

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;


public class GOOGLE {

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter search key");
        String key = scan.nextLine();
        String keyUpdated = key.replaceAll("\\s", "+");

        System.out.println(keyUpdated);

        try {

            URL url = new URL("https://www.google.lk/search?q=" + keyUpdated);

            BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
            BufferedWriter writer = new BufferedWriter(new FileWriter(key + ".html"));

            String line;

            while ((line = reader.readLine()) != null) {

                writer.write(line);

                writer.newLine();
            }


            reader.close();
            writer.close();
        } catch (MalformedURLException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}

这就是我输入“计算机科学”作为关键词时得到的结果。

java.io.IOException: Server returned HTTP response code: 403 for URL: https://www.google.lk/search?q=computer+science
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1876)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1474)
    at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at java.net.URL.openStream(URL.java:1045)
    at GOOGLE.main(Google.java:23)

【问题讨论】:

标签: java url


【解决方案1】:

浏览器签名导致请求被拒绝。

看看这个帖子:

Why do I get a 403 error when I try open a URL

【讨论】:

    【解决方案2】:

    正如我的评论链接的答案或@Eric Snider 的答案中所解释的,问题出在用于调用 Google 的用户代理上。为了提供有效的用户代理,您可以向 VM 添加以下选项(或使用其他用户代理,如果您愿意):

    java -Dhttp.agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0" <program_name>
    

    或者在运行时,使用下面的方法:

    System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:57.0) Gecko/20100101 Firefox/57.0");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-04-10
      • 2018-10-03
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 2023-03-20
      • 2011-05-21
      • 2014-11-02
      相关资源
      最近更新 更多