如何在android上为这个json做一个Http GET请求?

时间:2017-05-08 19:34:33

标签: java android http server get

[{   “名”:“乔治”,   “ID”: “2222”,   “姓氏”:“WIST”   “日期”: “07/08/07” }, {   “名”:“阿龙”,   “ID”: “1111”,   “姓氏”:“BORRIS”   “日期”:“09年6月6日” }]

1 个答案:

答案 0 :(得分:0)

您可以使用Volley库。 Android volley是一个网络库,用于使网络调用更容易,更快,而无需编写大量代码。

要使用Volley,您必须在dependencies文件中添加以下build.gradle

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

的非常好的教程

希望这会有所帮助〜