我是Android新手,我正在开发Android应用,我想从网址获取JSON数据:URL
我有以下代码:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class SingleContactActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
String url = "http://ana.fm/api/article/256281468161349/";
TextView title = (TextView) findViewById(R.id.single_article_title);
TextView desc = (TextView) findViewById(R.id.single_article_desc);
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpGet myConnection = new HttpGet(url);
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try{
JSONObject parent_obj = new JSONObject(str);
JSONArray jArray= parent_obj.getJSONArray("article");
JSONObject json = jArray.getJSONObject(0);
title.setText(json.getString("title"));
desc.setText(json.getString("description"));
} catch ( JSONException e) {
e.printStackTrace();
}
}
}
这是article.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Article Cover Photo -->
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_cover_photo"
android:layout_gravity="center_horizontal" />
<!-- Article Title -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_title"
android:layout_gravity="center_horizontal"
android:textColor="#acacac" />
<!-- Article Description -->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/single_article_desc"
android:layout_gravity="center_horizontal" />
</LinearLayout>
我在AndroidManifest.xml中设置了互联网权限:
<uses-permission android:name="android.permission.INTERNET" />
但是当我运行模拟器时,我得到: 空值 空
我的代码中找不到任何错误。
我使用了这段代码:
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
public class SingleContactActivity extends Activity {
public static String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView title;
TextView desc;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
title = (TextView) findViewById(R.id.single_article_title);
desc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING THE ARTICLE CONTENTS IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, Void> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
HttpResponse httpResponse;
HttpEntity httpEntity;
protected void onPreExecute() {
progressDialog.setMessage("Downloading article...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected Void doInBackground(String... params) {
String url_select = myArticleUrl;
// Set up HTTP Get
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url_select);
try {
httpResponse = httpClient.execute(httpGet);
result = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void v) {
//parse JSON data
try {
JSONObject parent_obj = new JSONObject(result);
JSONArray jArray= parent_obj.getJSONArray("article");
JSONObject json = jArray.getJSONObject(0);
title.setText(json.getString("title"));
desc.setText(json.getString("description"));
this.progressDialog.dismiss();
} catch (JSONException e) {
Log.e("JSONException", "Error: " + e.toString());
} // catch (JSONException e)
}
}
}
但是现在我需要处理HTML标签,有人知道我如何处理JSON中的HTML标签吗?
答案 0 :(得分:2)
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
public class SingleContactActivity extends Activity {
String myArticleUrl = "http://ana.fm/api/article/256281468161349/";
TextView txtTitle;
TextView txtDesc;
JSONParser jParser = new JSONParser();
JSONArray articles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.article);
txtTitle = (TextView) findViewById(R.id.single_article_title);
txtDesc = (TextView) findViewById(R.id.single_article_desc);
new LoadAllArticles().execute();
}
// LOADING ALL ARTICLES IN THE BACKGROUND
class LoadAllArticles extends AsyncTask<String, String, String> {
private ProgressDialog progressDialog = new ProgressDialog(SingleContactActivity.this);
InputStream inputStream = null;
String result = "";
String title = "";
String description = "";
protected void onPreExecute() {
progressDialog.setMessage("Downloading articles...");
progressDialog.show();
progressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface arg0) {
LoadAllArticles.this.cancel(true);
}
});
}
@Override
protected String doInBackground(String... params) {
String url_select = myArticleUrl;
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
JSONObject json = jParser.makeHttpRequest(url_select,
"GET", param); // Change "GET" to "POST" if you want the POST method
articles = json.getJSONArray("article");
JSONObject jsonObj = articles.getJSONObject(0);
title = jsonObj.getString("title");
description = jsonObj.getString("description");
}
catch (IllegalStateException e3) {
Log.e("IllegalStateException", e3.toString());
e3.printStackTrace();
}
catch (JSONException e5) {
Log.e("JSONException", e5.toString());
e5.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
try {
String newTitle = Html.fromHtml(title).toString();
txtTitle.setText(newTitle);
String newDesc = Html.fromHtml(description).toString();
txtDesc.setText(newDesc);
progressDialog.dismiss();
} catch (Exception e) {
Log.e("JSONException", "Error: " + e.toString());
}
}
}
}
你需要JSONParser
类:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
试试这个,它对我有用,我可以看到一堆阿拉伯语文本......
答案 1 :(得分:1)
您可以使用GSON代替肛门解析 。您将获得您的出版物是java对象。