Get JSON Data from URL Using Android?

后端 未结 8 2069
长发绾君心
长发绾君心 2020-11-28 04:48

I am trying to get JSON data by parsing login url with username and password. I have tried by using below code but I can\'t get any responses. Please help me.

I am u

8条回答
  •  死守一世寂寞
    2020-11-28 05:13

    Here in this snippet, we will see a volley method, add below dependency in-app level gradle file

    1. compile 'com.android.volley:volley:1.1.1' -> adding volley dependency.
    2. implementation 'com.google.code.gson:gson:2.8.5' -> adding gson for JSON data manipulation in android.

    Dummy URL -> https://jsonplaceholder.typicode.com/users (HTTP GET Method Request)

    public void getdata(){
        Response.Listener response_listener = new Response.Listener() {
            @Override
            public void onResponse(String response) {
                Log.e("Response",response);
                try {
                    JSONArray jsonArray = new JSONArray(response);
                    JSONObject jsonObject = jsonArray.getJSONObject(0).getJSONObject("address").getJSONObject("geo");
                    Log.e("lat",jsonObject.getString("lat");
                    Log.e("lng",jsonObject.getString("lng");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };
    
    
        Response.ErrorListener response_error_listener = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError || error instanceof NoConnectionError) {
                    //TODO
                } else if (error instanceof AuthFailureError) {
                    //TODO
                } else if (error instanceof ServerError) {
                    //TODO
                } else if (error instanceof NetworkError) {
                    //TODO
                } else if (error instanceof ParseError) {
                    //TODO
                }
            }
        };
    
        StringRequest stringRequest = new StringRequest(Request.Method.GET, "https://jsonplaceholder.typicode.com/users",response_listener,response_error_listener);
        getRequestQueue().add(stringRequest);
    }   
    
    public RequestQueue getRequestQueue() {
        //requestQueue is used to stack your request and handles your cache.
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(getApplicationContext());
        }
        return mRequestQueue;
    }
    

    Visit https://github.com/JainaTrivedi/AndroidSnippet-/blob/master/Snippets/VolleyActivity.java

提交回复
热议问题