刚学到网络通信,使用HTTP 的get方法做了个翻译的功能。初学者,自己记录下,自娱自乐。
一、到有道翻译申请个key,以便使用它提供的API来获取翻译结果。
这是我申请的,直接用我的也可以:"http://fanyi.youdao.com/openapi.do?keyfrom=testHttpGet2015&key=118817694&type=data&doctype=xml&version=1.1&q=good"
二、代码编写
1、布局如下:
<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">
<EditText
android:id="@+id/etWords"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入要翻译的内容" />
<Button
android:id="@+id/btnTranslation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="翻译" />
<TextView
android:text="结果如下:"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/tvResult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
</ScrollView>
</LinearLayout>
2、Manifest中添加INTERNET权限
<uses-permission android:name="android.permission.INTERNET" />
3、java代码
尝试以下几种通信方式:
(1)使用http的get方法
public class MainActivity extends Activity {
private TextView tv;
private EditText et;
public static final String FULL_URL = "http://fanyi.youdao.com/openapi.do?keyfrom=testHttpGet2015&key=118817694&type=data&doctype=xml&version=1.1&q=";
private List<String> textList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvResult);
et = (EditText) findViewById(R.id.etWords);
findViewById(R.id.btnTranslation).setOnClickListener(clickListener);
}
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
textList.clear();
tv.setText("");
readYoudaoResult(FULL_URL + et.getText().toString());
}
};
private void readYoudaoResult(String fullUrl) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
Element element = document.getDocumentElement();
//基本解释
Node translation = element.getElementsByTagName("translation").item(0);
if (translation != null) {
textList.add(translation.getTextContent() + "\n");
}
//发音及翻译
Node ukPhonetic = element.getElementsByTagName("uk-phonetic").item(0);
if (ukPhonetic != null) {
textList.add("英式发音: [" + ukPhonetic.getTextContent() + "]\n");
}
Node usPhonetic = element.getElementsByTagName("us-phonetic").item(0);
if (usPhonetic != null) {
textList.add("美式发音: [" + usPhonetic.getTextContent() + "]\n");
}
Node explains = element.getElementsByTagName("explains").item(0);
if (explains != null) {
textList.add("基本释义:" + explains.getTextContent());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
for (String children : textList) {
tv.append(children);
}
super.onPostExecute(s);
}
}.execute(fullUrl);
}
}
(2)使用http的post方法
public class MainActivity extends Activity {
private TextView tv;
private EditText et;
public static final String TRANSLATE_URL = "http://fanyi.youdao.com/openapi.do";
public static final String TRANSLATE_ENTITY = "keyfrom=testHttpGet2015&key=118817694&type=data&doctype=xml&version=1.1&q=";
private List<String> textList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvResult);
et = (EditText) findViewById(R.id.etWords);
findViewById(R.id.btnTranslation).setOnClickListener(clickListener);
}
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
textList.clear();
tv.setText("");
readYoudaoResult(TRANSLATE_URL, TRANSLATE_ENTITY + et.getText().toString());
}
};
private void readYoudaoResult(String translateUrl, String translateEntity) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
BufferedWriter bw = new BufferedWriter(osw);
bw.write(params[1]);
bw.flush();
bw.close();
osw.close();
InputStream is = connection.getInputStream();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
is.close();
Element element = document.getDocumentElement();
//基本解释
Node translation = element.getElementsByTagName("translation").item(0);
if (translation != null) {
textList.add(translation.getTextContent() + "\n");
}
//发音及翻译
Node ukPhonetic = element.getElementsByTagName("uk-phonetic").item(0);
if (ukPhonetic != null) {
textList.add("英式发音: [" + ukPhonetic.getTextContent() + "]\n");
}
Node usPhonetic = element.getElementsByTagName("us-phonetic").item(0);
if (usPhonetic != null) {
textList.add("美式发音: [" + usPhonetic.getTextContent() + "]\n");
}
Node explains = element.getElementsByTagName("explains").item(0);
if (explains != null) {
textList.add("基本释义:" + explains.getTextContent());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
for (String children : textList) {
tv.append(children);
}
super.onPostExecute(s);
}
}.execute(translateUrl, translateEntity);
}
}
(3)使用httpClient的get方法
public class MainActivity extends Activity {
private TextView tv;
private EditText et;
public static final String FULL_URL = "http://fanyi.youdao.com/openapi.do?keyfrom=testHttpGet2015&key=118817694&type=data&doctype=xml&version=1.1&q=";
private List<String> textList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvResult);
et = (EditText) findViewById(R.id.etWords);
findViewById(R.id.btnTranslation).setOnClickListener(clickListener);
}
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
textList.clear();
tv.setText("");
readYoudaoResult(FULL_URL + et.getText().toString());
}
};
private void readYoudaoResult(String fullUrl) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
String stringURL = params[0];
HttpGet get = new HttpGet(stringURL);
HttpResponse response = client.execute(get);
String buffer = EntityUtils.toString(response.getEntity());
InputStream is = new ByteArrayInputStream(buffer.getBytes("utf-8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
Element element = document.getDocumentElement();
//基本解释
Node translation = element.getElementsByTagName("translation").item(0);
if (translation != null) {
textList.add(translation.getTextContent() + "\n");
}
//发音及翻译
Node ukPhonetic = element.getElementsByTagName("uk-phonetic").item(0);
if (ukPhonetic != null) {
textList.add("英式发音: [" + ukPhonetic.getTextContent() + "]\n");
}
Node usPhonetic = element.getElementsByTagName("us-phonetic").item(0);
if (usPhonetic != null) {
textList.add("美式发音: [" + usPhonetic.getTextContent() + "]\n");
}
Node explains = element.getElementsByTagName("explains").item(0);
if (explains != null) {
textList.add("基本释义:" + explains.getTextContent());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
for (String children : textList) {
tv.append(children);
}
super.onPostExecute(s);
}
}.execute(fullUrl);
}
}
(4)使用httpClient的post方法
public class MainActivity extends Activity {
private TextView tv;
private EditText et;
public static final String TRANSLATE_URL = "http://fanyi.youdao.com/openapi.do";
public static final String KEY_FROM = "keyfrom";
public static final String KEY_FROM_VALUE = "testHttpGet2015";
public static final String KEY = "key";
public static final String KEY_VALUE = "118817694";
public static final String TYPE = "type";
public static final String TYPE_VALUE = "data";
public static final String DOC_TYPE = "doctype";
public static final String DOC_TYPE_VALUE = "xml";
public static final String VERSION = "version";
public static final String VERSION_VALUE = "1.1";
public static final String TRANSLATE_TEXT = "q";
private List<String> textList = new ArrayList<>();
private HttpClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.tvResult);
et = (EditText) findViewById(R.id.etWords);
client = new DefaultHttpClient();
findViewById(R.id.btnTranslation).setOnClickListener(clickListener);
}
private View.OnClickListener clickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
textList.clear();
tv.setText("");
readYoudaoResult(TRANSLATE_URL, et.getText().toString());
}
};
private void readYoudaoResult(String translateUrl, String translateEntity) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... params) {
try {
String stringURL = params[0];
HttpPost post = new HttpPost(stringURL);
List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
list.add(new BasicNameValuePair(KEY_FROM, KEY_FROM_VALUE));
list.add(new BasicNameValuePair(KEY, KEY_VALUE));
list.add(new BasicNameValuePair(TYPE, TYPE_VALUE));
list.add(new BasicNameValuePair(DOC_TYPE, DOC_TYPE_VALUE));
list.add(new BasicNameValuePair(VERSION, VERSION_VALUE));
list.add(new BasicNameValuePair(TRANSLATE_TEXT, params[1]));
post.setEntity(new UrlEncodedFormEntity(list));
HttpResponse response = client.execute(post);
String buffer = EntityUtils.toString(response.getEntity());
InputStream is = new ByteArrayInputStream(buffer.getBytes("utf-8"));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(is);
is.close();
Element element = document.getDocumentElement();
//基本解释
Node translation = element.getElementsByTagName("translation").item(0);
if (translation != null) {
textList.add(translation.getTextContent() + "\n");
}
//发音及翻译
Node ukPhonetic = element.getElementsByTagName("uk-phonetic").item(0);
if (ukPhonetic != null) {
textList.add("英式发音: [" + ukPhonetic.getTextContent() + "]\n");
}
Node usPhonetic = element.getElementsByTagName("us-phonetic").item(0);
if (usPhonetic != null) {
textList.add("美式发音: [" + usPhonetic.getTextContent() + "]\n");
}
Node explains = element.getElementsByTagName("explains").item(0);
if (explains != null) {
textList.add("基本释义:" + explains.getTextContent());
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
for (String children : textList) {
tv.append(children);
}
super.onPostExecute(s);
}
}.execute(translateUrl, translateEntity);
}
}
4、运行结果截图