2011-12-24 31 views
1

我米使用FALCON語義搜索引擎的RESTful API &寫了這個程序 ,但沒有得到應該從搜索engine.Please迴應的結果看代碼&幫我弄的URI。如何使用獵鷹的RESTful API

package httpProject; 

import java.io.*; 
import java.net.*; 
import java.lang.*; 

public class HTTPRequestPoster { 
    public String sendGetRequest(String endpoint, String requestParameters) { 
     String result = null; 
     if (endpoint.startsWith("http://")) { 
      try { 
       String urlStr = endpoint; 
       if (requestParameters != null && requestParameters.length() > 0) { 
        urlStr += "?" + requestParameters; 
       } 
       URL url = new URL(urlStr); 
       URLConnection conn = url.openConnection(); 

       // Get the response 
       BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); 
       StringBuffer sb = new StringBuffer(); 
       String line; 
       while ((line = rd.readLine()) != null) { 
        sb.append(line); 
       } 
       rd.close(); 
       result = sb.toString(); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 
     } 
     return result; 
    } 

    /** 
    * @param args 
    * @throws UnsupportedEncodingException 
    */ 
    public static void main(String[] args) throws UnsupportedEncodingException { 
     // TODO Auto-generated method stub 
     //HTTPRequestPoster a = new HTTPRequestPoster();// 
     HTTPRequestPoster astring = new HTTPRequestPoster(); 
     String param = "query=Person"; 
     String stringtoreverse = URLEncoder.encode(param, "UTF-8"); 
     astring.sendGetRequest("http://ws.nju.edu.cn/falcons/api/classsearch.jsp", stringtoreverse); 
     astring.toString(); 

     System.out.println(astring); 
     //PrintStream.class.toString(); 
    } 
} 
+0

這不是你的問題,但你永遠需要做'進口的java.lang。*;'如Java這是否自動爲您。總是有。 – 2011-12-24 13:37:19

+0

亞那是真的,但刪除導入java.lang。*後,它不會工作。 – 2011-12-24 16:39:36

+0

刪除之後無法使用?!要麼你選擇與HTTPRequestPoster相同的軟件包中的類名稱非常不恰當,要麼這個世界真的很奇怪。 – 2011-12-24 18:48:35

回答

1

你做所有繁重的任務,除了兩個小問題:

  • URLEncoder.encode(...)不應該被用在這裏。 Javadoc表示它將字符串翻譯爲application/x-www-form-urlencoded格式,即在執行POST時。

  • astring.sendGetRequest(...)而不是astring本身應該用作結果。

以下工作:

public static void main(String[] args) throws UnsupportedEncodingException { 
    // TODO Auto-generated method stub 
    //HTTPRequestPoster a = new HTTPRequestPoster();// 
    HTTPRequestPoster astring = new HTTPRequestPoster(); 
    String param = "query=Person"; 
    String result = astring.sendGetRequest("http://ws.nju.edu.cn/falcons/api/classsearch.jsp", param); 

    System.out.println(result); 
} 
+0

感謝您的建議,但我需要以UTF-8格式編碼字符串 – 2011-12-24 16:34:30

+0

它是Java,所以您不需要明確地這樣做。 – edwardw 2011-12-24 17:14:26