本文将创建一个App,通过使用网易的有道词典的API进行翻译结果的获取,以及结合之前学习的XML和JSON进行数据的解析(本文是根据学习极客学院的视频所写)
划红线的标出的是使用API的数据接口
然后开始写代码吧
在主Activity的布局文件里放置一个EditTex (输入要翻译的内容)
button (提交)
spinner(选择传回的数据格式是xml还是json)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<EditText
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:id="@+id/etTranslate"
/>
<Spinner
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:entries="@array/entries"
android:id="@+id/spinner">
Spinner>
LinearLayout>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="获取网页内容"
android:id="@+id/btn_get"/>
<TextView
android:layout_weight="1"
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
LinearLayout>
上面的spinner中的entries的值保存在vaules/data.xml文件中
<resources>
<string-array name="entries">
<item>接收JSON数据item>
<item>接受XML数据item>
string-array>
resources>
在MainActivity.java 中的oncreate 中找到上面定义的控件,为按钮设置点击事件,在点击事件中,新建一个AsyncTask用于同步接收数据
etTranslate = (EditText) findViewById(R.id.etTranslate);
tv = (TextView) findViewById(R.id.tv);
btn_get = (Button) findViewById(R.id.btn_get);
btn_get.setOnClickListener(new View.OnClickListener() {
// String url = "http://fanyi.youdao.com/openapi.do?keyfrom=SkyHttpGetTest&" +
// "keyfrom=54532393523935&type=data&doctype=json&version=1.1&q=" + etTranslate.getText().toString().trim();
@Override
public void onClick(View v) {
String url = "";
if (spinner.getSelectedItemPosition() == 0)
url = "http://fanyi.youdao.com/openapi.do?keyfrom=SkyHttpGetTest&key=545323935&type=data&doctype=json&version=1.1&q=" + etTranslate.getText().toString().trim();
else
url = "http://fanyi.youdao.com/openapi.do?keyfrom=SkyHttpGetTest&key=545323935&type=data&doctype=xml&version=1.1&q=" + etTranslate.getText().toString().trim();
tv.setText("");
new AsyncTask() {
@Override
protected String doInBackground(String... params) {
URL url = null;
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String str;
StringBuffer builder = new StringBuffer();
while ((str = br.readLine()) != null) {
builder.append(str);
}
br.close();
return builder.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
tv.setText("");
// tv.append(JSONTransform(s));
if (spinner.getSelectedItemPosition() == 0)
tv.append(JSONTransform(s));
else
tv.append(XMLTransform(s));
super.onPostExecute(s);
}
}.execute(url);
}
});
简单的讲解上面的代码:
在新建AsyncTask时要指定传入的参数类型,刷新时传入的参数类型,以及提交后的传出参数类型
new AsyncTask(paramsType,progressType,resultsType);
然后必须重写一个方法doInBackground(String… params)这个方法有点像新建一个Runable的run()方法,要同步执行的代码就写在这里面
接着我们要获取使用和http的get方法取得翻译的数据,在上面我们定义了一个String url,url 就是上面截图中划红线的字串,有两种分别对应JSON和xml,通过AsyncTask<>().execute(url)传入到AsyncTask中,doBackground中的String params 接收的就是这个url,所以我们在doBackground(String..params)函数中先新建
URL url=new URL(params[0]);
//获得连接
URLConnection connection=url.openConnection();
//获取数据
InputStream in=connection.getInputStream();
通过对inputStream 包装,将数据读到字符串中,将字符串返回。接着重写onPostExecute(String s),这个s就是刚刚在doBackground中返回的字符串
在onPostExecute中判断当前下拉单选择的是那种数据传递方式调用不同的数据解析方式,将解析的数据呈现到textView中
解析函数
//有道传回的XML数据解析
private String XMLTransform(String data) {
StringBuffer buffer = new StringBuffer();
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
StringReader sr = new StringReader(data);
InputSource in = new InputSource(sr);
Document document = factory.newDocumentBuilder().parse(in);
Element errorCode = (Element) document.getElementsByTagName("errorCode").item(0);
Element translation = (Element) document.getElementsByTagName("translation").item(0);
NodeList paragraphs = translation.getElementsByTagName("paragraph");
for (int i = 0; i < paragraphs.getLength(); i++) {
Element paragraph = (Element) paragraphs.item(0);
buffer.append(paragraph.getTextContent() + ", ");
}
buffer.append("\n基本释义:\n音标\n");
Element basic = (Element) document.getElementsByTagName("basic").item(0);
Element us_phonetic = (Element) basic.getElementsByTagName("us-phonetic").item(0);
Element uk_phonetic = (Element) basic.getElementsByTagName("uk-phonetic").item(0);
if (us_phonetic!= null)
buffer.append("美式音标:" + us_phonetic.getTextContent() + "\n");
if (uk_phonetic!= null)
buffer.append("英式音标:" + uk_phonetic.getTextContent() + "\n");
Element explains = (Element) basic.getElementsByTagName("explains").item(0);
Element ex = (Element) explains.getElementsByTagName("ex").item(0);
buffer.append(ex.getTextContent() + "\n");
buffer.append("网络释义:\n");
Element web = (Element) document.getElementsByTagName("web").item(0);
NodeList arrExplain = web.getElementsByTagName("explain");
for (int i = 0; i < arrExplain.getLength(); i++) {
Element explain = (Element) arrExplain.item(i);
Element key = (Element) explain.getElementsByTagName("key").item(0);
buffer.append(key.getTextContent() + "\n");
Element value = (Element) explain.getElementsByTagName("value").item(0);
NodeList exs = value.getElementsByTagName("ex");
for (int j = 0; j < exs.getLength(); j++) {
Element exTemp = (Element) exs.item(j);
buffer.append(exTemp.getTextContent() + " ");
}
buffer.append("\n");
}
} catch (ParserConfigurationException e) {
Toast.makeText(MainActivity.this, "Parse", Toast.LENGTH_SHORT).show();
} catch (SAXException e) {
Toast.makeText(MainActivity.this, "SAX", Toast.LENGTH_SHORT).show();
e.printStackTrace();
} catch (IOException e) {
Toast.makeText(MainActivity.this, "IOE", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return buffer.toString();
}
//有道传回的JSON数据解析
private String JSONTransform(String data) {
StringBuffer buff = new StringBuffer();
try {
JSONObject root = new JSONObject(data);
JSONArray arr = root.getJSONArray("translation");
buff.append("有道翻译:");
for (int i = 0; i < arr.length(); i++) {
buff.append(arr.get(i).toString() + ", ");
}
buff.append("\n" + "基本词典:\n ");
JSONObject basic = root.getJSONObject("basic");
buff.append("发音-" + basic.getString("phonetic") + "\n");
if (basic.get("uk-phonetic") != null)
buff.append("英式发音-" + basic.getString("phonetic") + "\n");
if (basic.get("us-phonetic") != null)
buff.append("美式发音-" + basic.getString("phonetic") + "\n");
buff.append("基本词典解释:\n");
JSONArray explains = basic.getJSONArray("explains");
for (int i = 0; i < explains.length(); i++) {
buff.append(explains.get(i).toString() + ", ");
}
buff.append("\n" + "网络词典:\n ");
JSONArray web = root.getJSONArray("web");
JSONArray value = ((JSONObject) web.get(0)).getJSONArray("value");
for (int i = 0; i < explains.length(); i++) {
buff.append(value.get(i).toString() + ", ");
}
} catch (JSONException e) {
e.printStackTrace();
}
return buff.toString();
}