首页 > 解决方案 > 如何在不使用 Android 中的任何 3rd 方库的情况下从基于 json 的 api 获取 json 数据?

问题描述

我想从 web api 获取 json 数据,我以前使用 Retrofit,但我不想使用任何第三方库。

我知道我可以使用HttpURLConnection,或者HttpClient没有合适的帖子,而且它们太旧了,在某些帖子中他们告诉它已被弃用,所以如果你有任何其他使用 HttpUrlConnection 和 HttpClient 的解决方案或不使用它,那么请让我知道。

GSONParser在我为此使用库之前,请告诉我如何解析该数据原因。

这是我的示例 api:

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

标签: javaandroidhttpurlconnectionandroid-networkingandroidhttpclient

解决方案


嘿,您可以使用您的方法检索您的数据,这取决于您。例如,我从未使用第三方库从服务器检索数据。

想一想:我可以FileContentReader用一个方法命名一个类,getContentFromUrl它会将您的 JSON 数据作为字符串获取,然后您可以使用JSONObjectJSONArray根据您的文件结构进行解析。

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();


    }
}

您可以在异步任务或任何后台任务中以这种方式使用代码:

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();}

}

推荐阅读