【发布时间】:2017-01-19 14:29:48
【问题描述】:
Volley 库在本地主机上运行时出现错误(无法连接到服务器),我的 Web 服务位于 asp.net 中。在浏览器上完美运行,但在我错的android设备上运行良好,请帮助我。我是安卓新手
public static final String JSON_URL="http://localhost:1462/Service1.svc/GetCities";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
btn = (Button) findViewById(R.id.btn);
linearLayoutManager = new LinearLayoutManager(this);
final MyAdapter ma = new MyAdapter(this, list);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(ma);
requestQueue = Volley.newRequestQueue(this);
/////////////////////////////////////////////////////////////
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Toast.makeText(MainActivity.this, "Response", Toast.LENGTH_SHORT).show();
try {
if (response.length() > 0) {
Toast.makeText(MainActivity.this, "Geting Response", Toast.LENGTH_SHORT).show();
list.clear();
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
Hotels h = new Hotels();
if (!jsonObject.isNull("City")) {
h.CityName = jsonObject.getString("City");
}
list.add(i, h);
}
ma.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// do something
Toast.makeText(MainActivity.this, "Cant connect to server", Toast.LENGTH_SHORT).show();
}
});
requestQueue.add(jsonArrayRequest);
}
});
}
【问题讨论】:
-
您的网址是
localhost,因为它从设备调用您的服务器,您需要您的服务器或域的 IP 地址 -
你不能使用
localhost作为模拟器它比你的计算机的差异,而不是localhost你可以使用10.0.2.2这将帮助你stackoverflow.com/questions/21510311/…设备使用你的机器的IP
标签: android web-services