-2
[{ “名”: “乔治”, “ID”: “2222”, “姓氏”: “WIST”, “日期”: “07/08/07” },{ “名 “:” 阿龙”, “ID”: “1111”, “姓氏”: “BORRIS”, “日期”: “09年6月6日” }]如何在Android上为此json创建Http GET请求?
[{ “名”: “乔治”, “ID”: “2222”, “姓氏”: “WIST”, “日期”: “07/08/07” },{ “名 “:” 阿龙”, “ID”: “1111”, “姓氏”: “BORRIS”, “日期”: “09年6月6日” }]如何在Android上为此json创建Http GET请求?
可以使用Volley
库。 Android volley是一个网络库,它可以在不编写大量代码的情况下更快速地实现联网调用。
要使用Volley
,你必须在你的build.gradle
文件中添加以下dependencies
:
dependencies {
.............
......................
compile 'com.mcxiaoke.volley:library-aar:1.0.0'
}
这是你需要的HTTP请求:
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
String url = "YOUR_API_URL";
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d("onResponse", response.toString());
// Here response is:
// [{ "name":"George", "id":"2222", "lastname":"wist", "date":"07/08/07" }, { "name":"aaron", "id":"1111", "lastname":"borris", "date":"06/06/09" }]
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response.get(i);
String name = person.getString("name");
String id = person.getString("id");
String lastname = phone.getString("lastname");
String date = phone.getString("date");
jsonResponse += "Name: " + name + "\n\n";
jsonResponse += "Id: " + id + "\n\n";
jsonResponse += "Lastname: " + lastname + "\n\n";
jsonResponse += "Date: " + date + "\n\n\n";
}
Log.d("onResponse", "JSON RESPONSE: " + jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("onErrorResponse", "Error: " + error.getMessage());
Toast.makeText(getApplicationContext(),
error.getMessage(), Toast.LENGTH_SHORT).show();
hidepDialog();
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
这里是一个非常好的教程的Android JSON parsing using Volley
希望这会有助于〜
使用'HttpURLConnection',OkHttp或其他HTTP客户端库对包含该JSON的某个服务器发出'GET'请求。 – CommonsWare
您是否遇到过在您最喜爱的搜索引擎中搜索基本关键字的常见方法的具体问题? – njzk2
您可以使用Volley库。 – FAT