【发布时间】:2018-12-15 19:19:05
【问题描述】:
我正在使用 Volley 进行网络连接并连接到我的 REST API。以下代码显示了我的 MainActivity 的 onCreate 方法。在这里,我想向我的 url 发出 GET 请求并接收 JSON 信息。但它不起作用。我在整个代码中做了不同的调试点。最后执行的是arrReq 的初始化。 onResponse 和 onErrorResponse 没有执行,不知道怎么回事。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupToolBar();
setupPagerAdapter();
setupFloatingButton();
getDeviceId();
JsonArrayRequest arrReq = new JsonArrayRequest(com.android.volley.Request.Method.GET, "http://localhost:8888/api/entities", null,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
// Check the length of our response (to see if there are any entities)
if (response.length() > 0) {
// There are entities so let's loop through them all.
for (int i = 0; i < response.length(); i++) {
try {
// Get each entity
JSONObject jsonObj = response.getJSONObject(i);
String locData = jsonObj.get("entity").toString();
} catch (JSONException e) {
// If there is an error then output this to the logs.
Log.e("Volley", "Invalid JSON Object.");
}
}
} else {
// There aren't any entities. So do nothing!
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// If there a HTTP error then add a note to our list.
Log.e("Volley", error.toString());
}
}
);
}
当我在设备上的浏览器中执行 url 时,会收到 JSON 代码:
{
"status":"success",
"data":[
{
"entity":"(17,)"
},
{
"entity":"(21,)"
},
{
"entity":"(201,)"
}
],
"message":"Retrieved entities"
}
日志没有显示任何错误。
【问题讨论】:
-
您是否在 onResponse 中记录了响应?
-
是的,但没有创建响应,因为 onResponse 尚未执行。
标签: android json rest http android-volley