对于我正在制作的应用,我需要从特定网址获取数据(CSV或JSON文件),但我无法让它工作。看来我必须在另一个线程(NetworkOnMainThreadException)中发出请求,但我不知道该怎么做。向网页发出请求并检索数据的正确方法是什么?
答案 0 :(得分:4)
即使它是重复的我也会回复。 最好的方法是使用异步方法:
class MyTask extends AsyncTask<Integer, Integer, String> {
@Override
protected String doInBackground(Integer... params) {
for (; count <= params[0]; count++) {
try {
Thread.sleep(1000);
publishProgress(count);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
JSONObject response = getJSONObjectFromURL("your http link"); // calls method to get JSON object
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return "Task Completed.";
}
@Override
protected void onPostExecute(String result) {
progressBar.setVisibility(View.GONE);
}
@Override
protected void onPreExecute() {
txt.setText("Task Starting...");
}
@Override
protected void onProgressUpdate(Integer... values) {
txt.setText("Running..."+ values[0]);
progressBar.setProgress(values[0]);
}
}
这是从http获取JSON并解析它的类。当你在url中调用方法传递时,你希望从中获取json对象。
public static JSONObject getJSONObjectFromURL(String urlString) throws IOException, JSONException {
HttpURLConnection urlConnection = null;
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setDoOutput(true);
urlConnection.connect();
BufferedReader br=new BufferedReader(new InputStreamReader(url.openStream()));
char[] buffer = new char[1024];
String jsonString = new String();
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line+"\n");
}
br.close();
jsonString = sb.toString();
System.out.println("JSON: " + jsonString);
urlConnection.disconnect();
return new JSONObject(jsonString);
}
答案 1 :(得分:2)
使用AsyncTask并将所有网络操作放入“doInBackground”并使用“onPostExecute”中的结果数据。
例如,您可以查看此帖子https://stackoverflow.com/a/18827536/2377961