- 申请有道API将获得以下链接
http://fanyi.youdao.com/openapi.do?keyfrom=mydictdemo&key=226680901&type=data&doctype=json&version=1.1&q=query
{
"translation": [
"查询"
],
"basic": {
"us-phonetic": "'kwɪri",
"phonetic": "'kwɪərɪ",
"uk-phonetic": "'kwɪərɪ",
"explains": [
"n. 疑问,质问;疑问号 ;[计] 查询",
"vi. 询问;表示怀疑",
"vt. 询问;对……表示疑问"
]
},
"query": "query",
"errorCode": 0,
"web": [
{
"value": [
"查询",
"疑问",
"询问"
],
"key": "Query"
},
{
"value": [
"空间查询",
"空间查询",
"空间索引"
],
"key": "Spatial query"
},
{
"value": [
"闪回查询",
"倒叙查询",
"回闪查询"
],
"key": "Flashback query"
}
]
}
向服务器发送请求获取JSON格式文本
/**
* 从指定的URL中获取文本
* @param urlPath
* @return
* @throws Exception
*/
public static String readParse(String urlPath) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inStream = conn.getInputStream();
while ((len = inStream.read(data)) != -1) {
outStream.write(data, 0, len);
}
inStream.close();
return new String(outStream.toByteArray());
}
解析JSON文本
String query = input.getText().toString();
english.setText(query);
pronuncation.setText("loading...");
chinese.setText("loading...");
Log.i("mytrace",query);
final String url = "http://fanyi.youdao.com/openapi.do?keyfrom=mydictdemo&key=226680901&type=data&doctype=json&version=1.1&q=" + query;
new Thread(new Runnable(){
@Override
public void run() {
try {
JSONObject result = new JSONObject(readParse(url));
String pro = "";
String exp = "";
JSONObject basic = null;
JSONArray explains = null;
try {
basic = new JSONObject(result.getString("basic"));
} catch (Exception e) {
e.printStackTrace();
}
try {
explains = new JSONArray(basic.getString("explains"));
} catch (Exception e) {
e.printStackTrace();
}
try {
pro = "美 " + "["+basic.getString("us-phonetic")+"]" + "\n";
pro += "英 " + "["+basic.getString("uk-phonetic")+"]";
} catch (Exception e) {
e.printStackTrace();
}
try {
for(int i=0;i<explains.length();i++){
Log.i("mytrace",explains.getString(i));
exp += explains.getString(i) +"\n";
}
} catch (Exception e) {
e.printStackTrace();
}
updateUi = new UpdateUi(pro, exp);
updateUiHandler.post(updateUi);
} catch (JSONException e1) {
e1.printStackTrace();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}).start();