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 に答える