Java HTTP URL连接响应

Java HTTP URL连接响应,java,Java,我试图点击URL并从我的Java代码中得到响应 我正在使用URLConnection获取此响应。并将此响应写入html文件 当在执行java类后在浏览器中打开这个html时,我得到的只是google主页,而不是结果 我的代码有什么问题,我的代码在这里 FileWriter fWriter = null; BufferedWriter writer = null; URL url = new URL("https://www.google.co.in/?gfe_rd=cr

我试图点击URL并从我的Java代码中得到响应

我正在使用URLConnection获取此响应。并将此响应写入html文件

当在执行java类后在浏览器中打开这个html时,我得到的只是google主页,而不是结果

我的代码有什么问题,我的代码在这里

    FileWriter fWriter = null;
    BufferedWriter writer = null;

    URL url = new URL("https://www.google.co.in/?gfe_rd=cr&ei=aS-BVpPGDOiK8Qea4aKIAw&gws_rd=ssl#q=google+post+request+from+java");
    byte[] encodedBytes = Base64.encodeBase64("root:pass".getBytes());
    String encoding = new String(encodedBytes);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("User-Agent", "Mozilla/5.0");
    connection.setRequestProperty("Accept-Charset", "UTF-8");
    connection.setDoInput(true);        
    connection.setRequestProperty("Authorization", "Basic " + encoding);
    connection.connect();

    InputStream content = (InputStream) connection.getInputStream();
    BufferedReader in = new BufferedReader(new InputStreamReader(content));
    String line;

    try {
        fWriter = new FileWriter(new File("f:\\fileName.html"));
        writer = new BufferedWriter(fWriter);
        while ((line = in.readLine()) != null) {
            String s = line.toString();
            writer.write(s);
            }
    writer.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

同样的代码在几天前可以工作,但现在不行。

这种搜索方法不建议失败,您必须用于这种工作

注意:谷歌使用了一些重定向和令牌,所以即使你能找到一个聪明的方法来处理它,从长远来看它也应该失败

编辑:

这是一个如何使用谷歌搜索API的例子,你可以得到你的工作以可靠的方式完成;有关更多信息,请参阅

public static void main(String[] args) throws Exception {
    String google = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=";
    String search = "stackoverflow";
    String charset = "UTF-8";

    URL url = new URL(google + URLEncoder.encode(search, charset));
    Reader reader = new InputStreamReader(url.openStream(), charset);
    GoogleResults results = new Gson().fromJson(reader, GoogleResults.class);

    // Show title and URL of 1st result.
    System.out.println(results.getResponseData().getResults().get(0).getTitle());
    System.out.println(results.getResponseData().getResults().get(0).getUrl());
}

原因是此url本身不返回搜索结果。你必须了解谷歌的工作流程才能理解它。在浏览器中打开此url并查看其源。在那里你只能看到很多javascript

实际上,在一个简短的总结中,google使用Ajax请求来处理搜索查询


要执行所需任务,您必须使用能够执行javascript/ajax的无头浏览器(最困难的方法),或者按照指示更好地使用。

这会在两天前返回结果页面作为响应,但不是现在。@user4120936请参阅我添加的注释以了解这方面的解释。您能建议一些url以使其正常工作吗?使用谷歌api@user4120936请查看“编辑”并从“源”中给出的链接中读取完整信息。这将返回两天前作为响应的结果页面,但不是现在。@user4120936使用了相同的url?