我想从Web api检索json数据,我以前使用过Retrofit,但是我不想使用任何第三方库。
我知道我可以使用HttpURLConnection
或HttpClient
,但没有合适的帖子,而且它们太旧了,在某些帖子中,他们告诉我们它已被弃用,所以如果您有使用HttpUrlConnection和HttpClient或不使用HttpUrlConnection的其他解决方案,请让我知道。
在我使用GSONParser
库之前,请告诉我如何解析该数据原因。
这是我的示例api:
答案 0 :(得分:2)
嘿,您可以使用取决于您的方法来检索数据。例如,我从未使用第三方库从服务器检索数据。
考虑一下:我可以使用方法FileContentReader
命名getContentFromUrl
的类,它将获取您的JSON数据为字符串,然后可以使用JSONObject
或{{1}进行解析},具体取决于您的文件结构。
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();
}
}