我正在使用Android Studio开发Android应用 和后端使用Asp.Net Web API。
Web Api Side
[System.Web.Http.AcceptVerbs("GET", "POST")]
[System.Web.Http.HttpGet]
public dynamic GetTest(string name)
{
List<person> persons = new List<person>()
{
new person { ID = 1, Name = "Loai" },
new person { ID = 2, Name = "rami" },
new person { ID = 3, Name = "Omar" },
new person { ID = 4, Name = name}
};
IEnumerable<person> p = persons.ToList();
return new { Students = p };
}
在此链接
http://qjtest.azurewebsites.net/api/test
如果您想设置名称参数值,可以使用
http://qjtest.azurewebsites.net/api/test?name=ayman
Android Studio Side
我已使用此代码
final String URL = "http://qjtest.azurewebsites.net/api/test";
HashMap<String, String> params = new HashMap<String, String>();
params.put("name", "ayman");
JsonObjectRequest req = new JsonObjectRequest(Request.Method.GET, URL, new JSONObject(params),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("Students");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject student = jsonArray.getJSONObject(i);
String ID = student.getString("ID");
String Name = student.getString("Name");
textview.append(ID + " - " + Name + "\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
}
});
requestQueue.add(req);
当我运行应用程序并按下按钮时,这是logcat中显示的错误
11-17 15:08:48.035 9628-9654/com.sqlite_test.alhalabi.loai.test_gson E/Volley: [155]
BasicNetwork.performRequest:意外的响应代码404 http://qjtest.azurewebsites.net/api/test 11-17 15:08:48.041 9628-9628 / com.sqlite_test.alhalabi.loai.test_gson E / Volley:1 2.onErrorResponse:错误:
答案 0 :(得分:1)
您可以参考以下示例:
df