2012-09-06 31 views
-1

我試圖編寫一個方法來調用服務,並獲取JSON數據回到Android應用程序。假設所有必要的gloable變量已經宣佈...Android的JSON解析,無法連接到服務

這些都是使用的lib IM:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.MalformedURLException; 
import java.net.URL; 
import java.net.URLConnection; 

import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

這裏是我的代碼:

public class JSONParser { 

String url = "http://gdata.youtube.com/feeds/api/users/eon/uploads?&v=2&max- results=50&alt=jsonc"; 

JSONObject jObj = null; 
JSONArray ja = null; 
String json = ""; 

// constructor 
public JSONParser() { 

} 



    public JSONObject getJSONFromUrl(String url){ 
    try { 
      URL urlGetter = new URL(url); 
     URLConnection tc = urlGetter.openConnection(); 
     BufferedReader in = new BufferedReader(new InputStreamReader(
       tc.getInputStream(), "iso-8859-1"), 8); 

      StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = in.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 


     json = sb.toString(); 
    } catch (MalformedURLException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

     //parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 
    return jObj; 
    } 

它只是沒有作用,我想運行在調試模式下,當它運行到這一行時:

BufferedReader in = new BufferedReader(new InputStreamReader(
      tc.getInputStream(), "iso-8859-1"), 8); 

它抱怨:java.net.UnknownHost例外:gdata.youtube.com 我不知道如何解決這個問題...任何建議? 感謝

順便說一下,在我的Android清單,我有許可證的互聯網已經:

如果你看看在瀏覽器中的網址,就可以看到TI的JSON格式...,它可以被連接...但我的代碼只是抱怨unknowhostexception ....「http://gdata.youtube.com/feeds/api/users/eon/uploads?& v = 2 & max-results = 50 & alt = jsonc「;

+0

你是通過移動/無線連接到互聯網嗎? – Bush

回答

3

請把權限在AndroidManifest.xml中

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