简体   繁体   中英

How to get json the data from json based api without using any 3rd party library in Android?

I want to fetch the json data from web api, I was previously using Retrofit for that, but I don't wanna use any third party library.

I know I can use HttpURLConnection or HttpClient but there is no proper post for that and they are too old, and in some post they were telling that it is deprecated, so if you have any other solution using HttpUrlConnection and HttpClient or without using that then please let me know.

And please tell me how to parse that data cause before that I was using GSONParser library for that.

Here is my example api:

https://www.mocky.io/v2/5b8126543400005b00ecb2fe

Hey you can retrieve your data using your methods, that depends on you. For example, I have never used a third party library to retrieve data from the server.

Think about this: a class that I can name FileContentReader with a method getContentFromUrl this will fetch your JSON data as string that you can then parse using JSONObject or JSONArray according to your file structure.

public class FileContentReader {
private Context appContext;

    public FileContentReader(Context context){
        this.appContext=context;
    }
    public String getContentFromUrl(String url)
    {
        StringBuilder content = new StringBuilder();
        try {
            URL u = new URL(url);
            HttpURLConnection uc = (HttpURLConnection) u.openConnection();
            if (uc.getResponseCode()==HttpURLConnection.HTTP_OK) {

                InputStream is = uc.getInputStream();
                BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
                String line;
                while ((line = br.readLine()) != null) {

                    content.append(line).append("\n");

                }

            }else{

                throw new IOException(uc.getResponseMessage());
            }
        } catch(StackOverflowError | Exception s){
                s.printStackTrace();
            } catch(Error e){
                e.printStackTrace();
            }


            return content.toString();


    }
}

You can use the code this way inside an asynchronous task or any background task :

FileContentReader fcr= new FileContentReader(getApplicationContext());

String data= fcr.getContentFromUrl("myurl");

if(!data.isEmpty())
{
try{
JSONArray ja = new JSONArray(data);
//... ou can then access and manupilate your data the way you want
}catch(JSONException e)
{
e.printStackTrace();}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM