[英]Download a JSON string from a website with AsyncTask
I have an android application and using AsyncTask I want to download a JSON file from a website. 我有一个android应用程序,使用AsyncTask我想从网站下载JSON文件。
So far I have 到目前为止,我有
public class DownloaderTask extends AsyncTask<String, Void, String[]> {
private MyActivity myactivity;
private Context context;
private String rawFeed[] = new String[3];
DownloaderTask(MyActivity parent) {
myactivity = parent;
context = parent.getApplicationContext();
}
@Override
protected String[] doInBackground(String... params) {
boolean complete = false;
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
for (int i = 0; i < params.length; i++) {
try {
URL url = new URL(params[i]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
input = connection.getInputStream();
}
catch (Exception e) {
}
}
return rawFeed;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String[] strings) {
if (myactivity != null) {
myactivity.setRefreshed(strings);
}
}
Im not sure how to continue from here 我不确定如何从这里继续
The website I'm downloading from is : https://d396qusza40orc.cloudfront.net/android%2FLabs%2FUserNotifications%2Ftaylorswift.txt 我正在从中下载的网站是: https : //d396qusza40orc.cloudfront.net/android%2FLabs%2FUserNotifications%2Ftaylorswift.txt
and when you go to the site it's just a page with a bunch of text on it, a JSON file. 当您访问该站点时,它只是一个页面,上面带有一堆文本,即一个JSON文件。
The parameters that get passed into the AsyncTask is an array of 3 strings, each string containing the URL that I need to download from 传递给AsyncTask的参数是3个字符串的数组,每个字符串包含我需要从中下载的URL
To read all the contents of an input stream I use: 要读取输入流的所有内容,请使用:
String inputStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
stringBuilder.append(line);
}
is.close();
}
catch (IOException e)
{ }
return stringBuilder.toString();
}
Then, to parse it as a JSON you just can user the Java JSONObject constructing it with that string. 然后,要将其解析为JSON,您只需使用Java JSONObject即可使用该字符串构造它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.