[英]How to get json the data from json based api without using any 3rd party library in Android?
我想从Web api获取json数据,我以前使用的是Retrofit,但是我不想使用任何第三方库。
我知道我可以使用HttpURLConnection
或HttpClient
但是没有合适的发布,而且它们太旧了,在某些发布中,他们告诉您不推荐使用它,因此,如果您有使用HttpUrlConnection和HttpClient的其他解决方案,或者不使用它们,那么请告诉我。
并且请告诉我在使用GSONParser
库之前如何解析该数据。
这是我的示例api:
嘿,您可以使用取决于您的方法来检索数据。 例如,我从未使用第三方库从服务器检索数据。
考虑一下:我可以使用getContentFromUrl
方法命名FileContentReader
的类,它将以字符串形式获取JSON数据,然后可以根据文件结构使用JSONObject
或JSONArray
进行解析。
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();}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.