java - 如何在不使用 Android 中的任何 3rd 方库的情况下从基于 json 的 api 获取 json 数据?
问题描述
我想从 web api 获取 json 数据,我以前使用 Retrofit,但我不想使用任何第三方库。
我知道我可以使用HttpURLConnection
,或者HttpClient
没有合适的帖子,而且它们太旧了,在某些帖子中他们告诉它已被弃用,所以如果你有任何其他使用 HttpUrlConnection 和 HttpClient 的解决方案或不使用它,那么请让我知道。
GSONParser
在我为此使用库之前,请告诉我如何解析该数据原因。
这是我的示例 api:
解决方案
嘿,您可以使用您的方法检索您的数据,这取决于您。例如,我从未使用第三方库从服务器检索数据。
想一想:我可以FileContentReader
用一个方法命名一个类,getContentFromUrl
它会将您的 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();}
}
推荐阅读
- wso2 - 如何从 Okta 自定义 SAML AuthnRequest 以添加 AuthnContextDecl
- sql - 创建触发器以在从帐户到帐户的交易后更新余额 - SQL Oracle
- ubuntu - 如何根据热目录修复 btrfs 错误
- android - flutter_recaptcha_v2 依赖于 http ^0.12.0+1 而 my_app 依赖于 http ^0.13.1
- css - TailwindCSS 布局中的溢出问题
- android - 违反流异常透明度:检测到来自另一个协程的发射
- ios - adjustsFontForContentSizeCategory 正在破坏 UIButton
- java - Integer 如何自动装箱到 Future
何时使用可调用? - fortran - 如何在 Fortran 95 中检测标准输入中的数据结束?
- git - 有没有办法将 git lfs 推送到裸存储库