2012-11-04 46 views
0

我想在某些使用java的網站上發出GET AJAX請求。在Java中的AJAX GET請求

我的代碼如下:

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中)。

回答

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(); } 
    } 
+0

仍然是相同的結果。其實,這裏沒有例外。 – Angstrem

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) { 
       } 
      } 
     } 

這是在我的項目工作正常碼的和平。 :)