0

我正在尝试使用 java 在某些站点上发出 GET AJAX 请求。

我的代码如下:

    String cookie = getRandomString(16); //Getting a random 32-symbol string

    String url = "https://e-kassa.org/core/ajax/stations_search.php?"
            + "q=%D0%BE&limit=10&timestamp=1352028872503";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    conn.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
    InputStream is = conn.getInputStream();

    int buffer;
    while((buffer = is.read()) != -1)
        System.out.print(buffer);

    is.close();
    conn.disconnect();

但问题是 InputStream 没有什么可以下载的。但如果我使用浏览器做同样的事情,我会得到一个响应,由以下格式的文本行组成:

CITY_NAME|SOME_DIGITS

那么,谁能告诉我,我怎样才能以适当的方式提出这样的请求?

UPD:没有 cookie 我有相同的行为(在浏览器中一切都很好,但在 Java 中不是)。

4

2 回答 2

1

你能试试:

BufferedReader rd = null;
        try {
            URL url = new URL("https://e-kassa.org/core/ajax/stations_search.php?"
            + "q=%D0%BE&limit=10&timestamp=1352028872503");
            URLConnection conn = url.openConnection();
            String cookie = (new RandomString(32)).nextString();
            conn.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
            // Get the response
            rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuffer sb = new StringBuffer();
            String line;
            while ((line = rd.readLine()) != null) {
                sb.append(line);
            }
            System.out.println(sb.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (rd != null) {
                try {
                    rd.close();
                } catch (IOException e) {
                }
            }
        }

这是在我的项目中正常工作的代码的和平。:)

于 2012-11-06T10:55:23.647 回答
0

试试下面的东西。

HttpURLConnection connection = null;
    try {
        String url = "https://e-kassa.org/core/ajax/stations_search.php?"
            + "q=%D0%BE&limit=10&timestamp=1352028872503";
        URL url = new URL(url);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Cookie", "PHPSESSID=" + cookie);
        connection.connect();
        connection.getInputStream();
        int buffer;
        while((buffer = is.read()) != -1)
           System.out.print(buffer);
    } catch (MalformedURLException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    } finally {
        if(null != connection) { connection.disconnect(); }
    }
于 2012-11-04T11:56:32.220 回答