-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