2013-10-28 57 views
0

我正在學習Android Studio中的android開發。我使用Android查詢庫輕鬆進行HTTP調用,以從我的Grails Web應用程序獲取JSON數據。在我的android UI中,我有一個按鈕和一個editText。我希望在點擊按鈕後顯示從服務器返回的JSON字符串。下面的代碼:Android查詢ajax無法從Grails網頁獲得json結果

public static class PlaceholderFragment extends Fragment { 
    private AQuery aq; 

    public PlaceholderFragment() { 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
      Bundle savedInstanceState) { 
     View rootView = inflater.inflate(R.layout.fragment_main, container, false); 
     aq = new AQuery(getActivity(), rootView); 
     aq.id(R.id.button1).clicked(this, "onButtonClick"); 
     return rootView; 
    } 

    public void onButtonClick(View view) { 
     String url = "http://localhost:8090/MyProject/main/index"; 
     aq.ajax(url, JSONObject.class, this, "jsonCallback"); 

    } 

    public void jsonCallback(String url, JSONObject json, AjaxStatus status){ 
     if(json != null){ 
      aq.id(R.id.editText).text(json.toString()); 
     }else{ 
      aq.id(R.id.editText).text(status.getMessage()); 
     } 
    } 
} 

在Grails的一面,我只是直接發送回一個JSON對象:

class MainController { 
    def re = ['name' : 'abc'] 

    def index() { 
     render re as JSON 
    } 
} 

我可以訪問我的Grails的Web URL在瀏覽器中,並得到正確的JSON數據:

{ 
    name: "abc" 
} 

如果我在虛擬設備中運行android應用程序,我剛剛收到「網絡錯誤」消息。返回的JSON對象爲null。

如果我使用相同的android代碼訪問http://ip.jsontest.com來代替我的Grails網址。我可以得到沒有網絡錯誤返回正確的json數據。爲什麼?

任何人都可以給我一些建議,讓Android查詢與Grails網絡一起工作嗎?

+0

如果android使用瀏覽器的原生ajax features/API,它可能是一個CORS問題。看看下面的grails插件:http://grails.org/plugin/cors – Gregg

+0

感謝您的回覆。但我不明白爲什麼相同的代碼可以訪問http://ip.jsontest.com並得到json結果,如果它是CORS問題?我想我需要在Garils身邊做點什麼。但不知道如何。 –

回答

0

最後,我找到了原因:

從Android模擬器在PC上訪問本地主機的Web應用程序,我們不能使用localhost作爲服務器的地址。我更改URL爲「http://10.0.3.2:8090/MyProject/main/index」(我使用Genymotion Android模擬器),它的工作原理。

0

如果您使用的是Genymotion Android模擬器,那麼URL應該像「//192.168.56.1:8090/MyProject/main/index」這是您的本地IP地址,或者如果您使用的是默認模擬器,那麼應​​該是像「//10.0.0.2:8090/MyProject/main/index」