我正在尝试从网站解析 json 内容并下载一些 html 文件而不是 json 对象。这是显示的代码和错误。(仅供参考,我正在解析 json 并将其显示在日志猫中)
这是 MainActivity.java
public class MainActivity extends Activity {
ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new MyAsyncTask().execute();
lv = (ListView) findViewById(R.id.listView1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyAsyncTask extends AsyncTask<String, String, String> {
String url = "http://walmartlabs.api.mashery.com/v1/taxonomy?format=json&apiKey=yhg57ygb3mdk8ywuwdsvgews";
ProgressDialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Please wait...");
dialog.show();
}
@Override
protected String doInBackground(String... params) {
JSONParser parser = new JSONParser();
JSONObject array = parser.getJSON(url);
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
这是解析器类:JSONParser.java
public class JSONParser {
JSONObject jarray;
String line;
JSONObject getJSON(String url) {
final StringBuilder sb = new StringBuilder();
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
/* HttpGet httpPost = new HttpGet(url); */
try {
HttpResponse httpRes = httpClient.execute(httpPost);
HttpEntity entity = httpRes.getEntity();
InputStream stream = entity.getContent();
final BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
while ((line = reader.readLine()) != null) {
sb.append(line);
Log.i("PARSED", line);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jarray = new JSONObject(sb.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jarray;
}
}
该图显示了从 json 中提取的数据及其错误