2012-02-11 69 views
3

我想獲得BING結果到JSON形式的查詢,然後使其JSON對象和執行一些事情。得到JSON響應在Android中的HTTP查詢

但我不能接收響應:(

我嘗試以下兩種方法

任何人可以幫助我解決問題

Approach1:?

URL searhURL; 
//String imageurl = "http://api.bing.net/json.aspx?AppID="+myBingAppID+"&Query="+formattedQuery+"&Sources=images"; 
String imageurl="http://www.bing.com/images/search?q="+formattedQuery+"&go=&qs=n&form=QBLH&filt=all"; 

    URL url = new URL(imageurl); 
    InputStream is = null; 

     URLConnection connection = url.openConnection(); 
     Log.d(LOGGER, "1.0"); 
     String line; 
     StringBuilder builder = new StringBuilder(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(
         connection.getInputStream())); //problem is here 
     Log.d(LOGGER, "2.0"); 
     while ((line = reader.readLine()) != null) { 
       builder.append(line); 
     } 
     Log.d(LOGGER, "3.0"); 

     jSONString = builder.toString(); 
     //after cutting off the junk, its ok 
     Log.d(LOGGER, "String is : "+jSONString); 
     JSONObject jSONObject = new JSONObject(jSONString); //whole json object 

正如你所看到的,我嘗試了使用API​​密鑰和不使用API​​密鑰。但是仍然有問題在線評論爲問題在這裏。

方法2

  String jsonString=""; 
     try { 
       URL url = new URL(imageurl); 
       Log.d(LOGGER, "1"); 
       BufferedReader in = new BufferedReader(new InputStreamReader( 
       url.openStream())); //problem here 
       Log.d(LOGGER, "2"); 
       String inputLine; 

       while ((inputLine = in.readLine()) != null) { 
       //JSON data get stored as a string 
       jsonString = inputLine; 

       } 
       Log.d(LOGGER, "3"); 
       in.close(); 
       Log.d(LOGGER, "String is : "+jsonString); 
} 
     catch (IOException e) { 
       e.printStackTrace(); 
       } 
+0

什麼問題? – 2012-02-11 18:57:21

+0

超出緩衝區讀取器的日誌語句不會顯示在log cat中。而且jsonString沒有被製作/顯示 – adityag 2012-02-11 19:04:38

+0

http://justpaste.it/qf4是確切的log cat語句。 – adityag 2012-02-11 21:28:37

回答

7

這就是爲什麼我們建議您始終包括logcat的輸出,因爲沒有辦法,我們可以計算出來離不開它。

添加到您的AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET" /> 

你得到你所使用的網絡SecurityException,因爲你還沒有告訴Android系統。

+0

非常感謝!這幫助了我:)我絕對忘了添加這個權限。 – adityag 2012-02-12 05:47:21

+1

不客氣,祝你好運。 – 2012-02-12 13:06:35