Get JSON Data from URL Using Android?

后端 未结 8 2061
长发绾君心
长发绾君心 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

    I feel your frustration.

    Android is crazy fragmented, and the the sheer amount of different examples on the web when searching is not helping.

    That said, I just completed a sample partly based on mustafasevgi sample, partly built from several other stackoverflow answers, I try to achieve this functionality, in the most simplistic way possible, I feel this is close to the goal.

    (Mind you, code should be easy to read and tweak, so it does not fit your json object perfectly, but should be super easy to edit, to fit any scenario)

    protected class yourDataTask extends AsyncTask<Void, Void, JSONObject>
    {
        @Override
        protected JSONObject doInBackground(Void... params)
        {
    
            String str="http://your.domain.here/yourSubMethod";
            URLConnection urlConn = null;
            BufferedReader bufferedReader = null;
            try
            {
                URL url = new URL(str);
                urlConn = url.openConnection();
                bufferedReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
    
                StringBuffer stringBuffer = new StringBuffer();
                String line;
                while ((line = bufferedReader.readLine()) != null)
                {
                    stringBuffer.append(line);
                }
    
                return new JSONObject(stringBuffer.toString());
            }
            catch(Exception ex)
            {
                Log.e("App", "yourDataTask", ex);
                return null;
            }
            finally
            {
                if(bufferedReader != null)
                {
                    try {
                        bufferedReader.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    
        @Override
        protected void onPostExecute(JSONObject response)
        {
            if(response != null)
            {
                try {
                    Log.e("App", "Success: " + response.getString("yourJsonElement") );
                } catch (JSONException ex) {
                    Log.e("App", "Failure", ex);
                }
            }
        }
    }
    

    This would be the json object it is targeted towards.

    {
        "yourJsonElement":"Hi, I'm a string",
        "anotherElement":"Ohh, why didn't you pick me"
    }
    

    It is working on my end, hope this is helpful to someone else out there.

    0 讨论(0)
  • 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<String> response_listener = new Response.Listener<String>() {
            @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

    0 讨论(0)
  • 2020-11-28 05:14
        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    String sResponse;
    StringBuilder s = new StringBuilder();
    
    while ((sResponse = reader.readLine()) != null) {
        s = s.append(sResponse);
    }
    Gson gson = new Gson();
    
    JSONObject jsonObject = new JSONObject(s.toString());
    String link = jsonObject.getString("Result");
    
    0 讨论(0)
  • 2020-11-28 05:17
    private class GetProfileRequestAsyncTasks extends AsyncTask<String, Void, JSONObject> {
    
        @Override
        protected void onPreExecute() {
    
        }
    
        @Override
        protected JSONObject doInBackground(String... urls) {
            if (urls.length > 0) {
                String url = urls[0];
                HttpClient httpClient = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(url);
                httpget.setHeader("x-li-format", "json");
                try {
                    HttpResponse response = httpClient.execute(httpget);
                    if (response != null) {
                        //If status is OK 200
                        if (response.getStatusLine().getStatusCode() == 200) {
                            String result = EntityUtils.toString(response.getEntity());
                            //Convert the string result to a JSON Object
                            return new JSONObject(result);
                        }
                    }
                } catch (IOException e) {
    
                } catch (JSONException e) {
                }
            }
            return null;
        }
        @Override
        protected void onPostExecute(JSONObject data) {
            if (data != null) {
                Log.d(TAG, String.valueOf(data));
            }
        }
    
    }
    
    0 讨论(0)
  • 2020-11-28 05:18

    Easy way to get JSON especially for Android SDK 23:

    public class MainActivity extends AppCompatActivity {
    
    Button btnHit;
    TextView txtJson;
    ProgressDialog pd;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        btnHit = (Button) findViewById(R.id.btnHit);
        txtJson = (TextView) findViewById(R.id.tvJsonItem);
    
        btnHit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new JsonTask().execute("Url address here");
            }
        });
    
    
    }
    
    
    private class JsonTask extends AsyncTask<String, String, String> {
    
        protected void onPreExecute() {
            super.onPreExecute();
    
            pd = new ProgressDialog(MainActivity.this);
            pd.setMessage("Please wait");
            pd.setCancelable(false);
            pd.show();
        }
    
        protected String doInBackground(String... params) {
    
    
            HttpURLConnection connection = null;
            BufferedReader reader = null;
    
            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
    
    
                InputStream stream = connection.getInputStream();
    
                reader = new BufferedReader(new InputStreamReader(stream));
    
                StringBuffer buffer = new StringBuffer();
                String line = "";
    
                while ((line = reader.readLine()) != null) {
                    buffer.append(line+"\n");
                    Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 
    
                }
    
                return buffer.toString();
    
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (pd.isShowing()){
                pd.dismiss();
            }
            txtJson.setText(result);
        }
    }
    }
    
    0 讨论(0)
  • 2020-11-28 05:24

    Don't know about android but in POJ I use

    public final class MyJSONObject extends JSONObject {
        public MyJSONObject(URL url) throws IOException {
            super(getServerData(url));
        }
        static String getServerData(URL url) throws IOException {
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            BufferedReader ir = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String text = ir.lines().collect(Collectors.joining("\n"));
            return (text);
        }
    }
    
    0 讨论(0)
提交回复
热议问题