Get JSON Data from URL Using Android?

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

    If you get the server response as a String, without using a third party library you can do

    JSONObject json = new JSONObject(response);
    JSONObject jsonResponse = json.getJSONObject("response");
    String team = jsonResponse.getString("Team");
    

    Here is the documentation

    Otherwise to parse json you can use Gson or Jackson

    EDIT without libraries (not tested)

    class retrievedata extends AsyncTask{
        @Override
        protected String doInBackground(Void... params) {
    
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;
    
            URL url;
            try {
                url = new URL("http://myurlhere.com");
                urlConnection.setRequestMethod("GET"); //Your method here 
                urlConnection.connect();
    
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));
    
                String line;
                while ((line = reader.readLine()) != null)
                    buffer.append(line + "\n");
    
                if (buffer.length() == 0)
                    return null;
    
                return buffer.toString();
            } catch (IOException e) {
                Log.e(TAG, "IO Exception", e);
                exception = e;
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        exception = e;
                        Log.e(TAG, "Error closing stream", e);
                    }
                }
            }
        }
    
        @Override
        protected void onPostExecute(String response) {
            if(response != null) {
                JSONObject json = new JSONObject(response);
                JSONObject jsonResponse = json.getJSONObject("response");
                String team = jsonResponse.getString("Team");
            }
        }
    }
    

提交回复
热议问题