Get JSON Data from URL Using Android?

后端 未结 8 2063
长发绾君心
长发绾君心 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
    {
        @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.

提交回复
热议问题