我在android学习Android开发。我使用Android查询库进行简单的HTTP调用,从Grails web应用程序中获取JSON数据。在我的android中,我有一个按钮和一个editText。我希望在单击按钮后显示从服务器返回的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上运行得很好吗?
发布于 2013-10-30 04:15:25
最后,我找到了原因:
从Android仿真器访问PC上的本地主机web应用程序时,不能使用本地主机作为服务器地址。我将URL更改为"http://10.0.3.2:8090/MyProject/main/index“(我使用Genymotion仿真程序),它可以工作。
发布于 2014-12-03 05:46:33
如果您正在使用Genymotion Android仿真器,那么URL应该是"//192.168.56.1:8090/MyProject/main/index“,这是您的本地ip地址,或者如果您使用的是默认仿真程序,则应该类似于"//10.0.0.2:8090/MyProject/main/index”
https://stackoverflow.com/questions/19644647
复制相似问题