中英翻譯(基于百度翻譯)

先來看效果圖

只做了簡單的在線翻譯,語音翻譯和圖片翻譯都要錢,哈哈

市面上有名氣的翻譯公司就是有道和百度了,有道嘗試了一下,分為API和SDK兩種,但是demo下載下來跑不了

百度的就是API,也很簡單,就是通過百度的協議去請求他們的服務器,得到翻譯后的值,每個月有200萬的免費,夠用了

百度文檔地址http://api.fanyi.baidu.com/api/trans/product/apidoc#joinFile

步驟:

java版demo下載地址https://fanyiapp.cdn.bcebos.com/api/demo/java.zip

下面是核心代碼

<?xml version="1.0" encoding="utf-8"?>
<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"><EditTextandroid:id="@+id/inputChinese"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="請輸入要翻譯的中文"android:singleLine="true" /><EditTextandroid:id="@+id/inputEnglish"android:layout_width="match_parent"android:layout_height="wrap_content"android:hint="請輸入要翻譯的英文"android:singleLine="true" /><TextViewandroid:id="@+id/translate"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="right"android:layout_margin="10dp"android:padding="10dp"android:text="翻譯"android:textSize="20sp" /><TextViewandroid:id="@+id/outputEnglish"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="5dp"tools:text="得到的英文" /><TextViewandroid:id="@+id/outputChinese"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="5dp"tools:text="得到的中文" /></LinearLayout>
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;public class MainActivity extends AppCompatActivity {private static final String APP_ID = "20190603000304432";private static final String SECURITY_KEY = "gZTcFc0TyR6tZS5FfmyA";private EditText inputChinese;private EditText inputEnglish;private TextView outputEnglish;private TextView outputChinese;private TextView translate;private TransApi api;private static final int CHINESE = 1;private static final int ENGLISH = 2;private static final String TO_ENGLISH = "en";private static final String TO_CHINESE = "zh";private Handler handler = new Handler() {@Overridepublic void handleMessage(Message msg) {super.handleMessage(msg);String str = String.valueOf(msg.obj);String value = parserJson(str);switch (msg.what) {case CHINESE:outputChinese.setText(value);break;case ENGLISH:outputEnglish.setText(value);break;}}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initView();api = new TransApi(APP_ID, SECURITY_KEY);translate.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {translate(inputChinese.getText().toString(), TO_ENGLISH);translate(inputEnglish.getText().toString(), TO_CHINESE);}});}private void initView() {inputChinese = findViewById(R.id.inputChinese);inputEnglish = findViewById(R.id.inputEnglish);outputEnglish = findViewById(R.id.outputEnglish);outputChinese = findViewById(R.id.outputChinese);translate = findViewById(R.id.translate);}private void translate(final String chinese, final String toLanguage) {new Thread(new Runnable() {@Overridepublic void run() {String transResult = api.getTransResult(chinese, "auto", toLanguage);Message message = new Message();switch (toLanguage) {case TO_CHINESE:message.what = CHINESE;break;case TO_ENGLISH:message.what = ENGLISH;break;}message.obj = transResult;handler.sendMessage(message);}}).start();}private String parserJson(String str) {try {JSONObject jsonObject = new JSONObject(str);JSONArray trans_result = jsonObject.getJSONArray("trans_result");JSONObject result = trans_result.getJSONObject(0);String dst = result.getString("dst");return dst;} catch (JSONException e) {e.printStackTrace();}return "";}
}
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;class HttpGet {protected static final int SOCKET_TIMEOUT = 10000; // 10Sprotected static final String GET = "GET";public static String get(String host, Map<String, String> params) {try {// 設置SSLContextSSLContext sslcontext = SSLContext.getInstance("TLS");sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);String sendUrl = getUrlWithQueryString(host, params);// System.out.println("URL:" + sendUrl);
URL uri = new URL(sendUrl); // 創建URL對象HttpURLConnection conn = (HttpURLConnection) uri.openConnection();if (conn instanceof HttpsURLConnection) {((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());}conn.setConnectTimeout(SOCKET_TIMEOUT); // 設置相應超時
            conn.setRequestMethod(GET);int statusCode = conn.getResponseCode();if (statusCode != HttpURLConnection.HTTP_OK) {System.out.println("Http錯誤碼:" + statusCode);}// 讀取服務器的數據InputStream is = conn.getInputStream();BufferedReader br = new BufferedReader(new InputStreamReader(is));StringBuilder builder = new StringBuilder();String line = null;while ((line = br.readLine()) != null) {builder.append(line);}String text = builder.toString();close(br); // 關閉數據流close(is); // 關閉數據流conn.disconnect(); // 斷開連接return text;} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} catch (KeyManagementException e) {e.printStackTrace();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return null;}public static String getUrlWithQueryString(String url, Map<String, String> params) {if (params == null) {return url;}StringBuilder builder = new StringBuilder(url);if (url.contains("?")) {builder.append("&");} else {builder.append("?");}int i = 0;for (String key : params.keySet()) {String value = params.get(key);if (value == null) { // 過濾空的keycontinue;}if (i != 0) {builder.append('&');}builder.append(key);builder.append('=');builder.append(encode(value));i++;}return builder.toString();}protected static void close(Closeable closeable) {if (closeable != null) {try {closeable.close();} catch (IOException e) {e.printStackTrace();}}}/*** 對輸入的字符串進行URL編碼, 即轉換為%20這種形式* * @param input 原文* @return URL編碼. 如果編碼失敗, 則返回原文*/public static String encode(String input) {if (input == null) {return "";}try {return URLEncoder.encode(input, "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}return input;}private static TrustManager myX509TrustManager = new X509TrustManager() {@Overridepublic X509Certificate[] getAcceptedIssuers() {return null;}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}};}
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;/*** MD5編碼相關的類** @author wangjingtao*/
public class MD5 {// 首先初始化一個字符數組,用來存放每個16進制字符private static final char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd','e', 'f'};/*** 獲得一個字符串的MD5值** @param input 輸入的字符串* @return 輸入字符串的MD5值*/public static String md5(String input) {if (input == null)return null;try {// 拿到一個MD5轉換器(如果想要SHA1參數換成”SHA1”)MessageDigest messageDigest = MessageDigest.getInstance("MD5");// 輸入的字符串轉換成字節數組byte[] inputByteArray = input.getBytes("utf-8");// inputByteArray是輸入字符串轉換得到的字節數組
            messageDigest.update(inputByteArray);// 轉換并返回結果,也是字節數組,包含16個元素byte[] resultByteArray = messageDigest.digest();// 字符數組轉換成字符串返回return byteArrayToHex(resultByteArray);} catch (NoSuchAlgorithmException e) {return null;} catch (UnsupportedEncodingException e) {e.printStackTrace();}return null;}/*** 獲取文件的MD5值** @param file* @return*/public static String md5(File file) {try {if (!file.isFile()) {System.err.println("文件" + file.getAbsolutePath() + "不存在或者不是文件");return null;}FileInputStream in = new FileInputStream(file);String result = md5(in);in.close();return result;} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}public static String md5(InputStream in) {try {MessageDigest messagedigest = MessageDigest.getInstance("MD5");byte[] buffer = new byte[1024];int read = 0;while ((read = in.read(buffer)) != -1) {messagedigest.update(buffer, 0, read);}in.close();String result = byteArrayToHex(messagedigest.digest());return result;} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return null;}private static String byteArrayToHex(byte[] byteArray) {// new一個字符數組,這個就是用來組成結果字符串的(解釋一下:一個byte是八位二進制,也就是2位十六進制字符(2的8次方等于16的2次方))char[] resultCharArray = new char[byteArray.length * 2];// 遍歷字節數組,通過位運算(位運算效率高),轉換成字符放到字符數組中去int index = 0;for (byte b : byteArray) {resultCharArray[index++] = hexDigits[b >>> 4 & 0xf];resultCharArray[index++] = hexDigits[b & 0xf];}// 字符數組組合成字符串返回return new String(resultCharArray);}}
import java.util.HashMap;
import java.util.Map;public class TransApi {private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";private String appid;private String securityKey;public TransApi(String appid, String securityKey) {this.appid = appid;this.securityKey = securityKey;}public String getTransResult(String query, String from, String to) {Map<String, String> params = buildParams(query, from, to);return HttpGet.get(TRANS_API_HOST, params);}private Map<String, String> buildParams(String query, String from, String to) {Map<String, String> params = new HashMap<String, String>();params.put("q", query);params.put("from", from);params.put("to", to);params.put("appid", appid);// 隨機數String salt = String.valueOf(System.currentTimeMillis());params.put("salt", salt);// 簽名String src = appid + query + salt + securityKey; // 加密前的原文params.put("sign", MD5.md5(src));return params;}}

歡迎關注我的微信公眾號:安卓圈

轉載于:https://www.cnblogs.com/anni-qianqian/p/10972828.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/247828.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/247828.shtml
英文地址,請注明出處:http://en.pswp.cn/news/247828.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Vue中使用input簡易的上傳圖片

<div class"boximg"><div class"topimg"><!-- <img :src"filePath" width"200px" height"170px" /> --></div><div class"botimg" click"imgClick()">上傳logo<…

jQuery選擇器之層級選擇器

文檔中的所有的節點之間都是有這樣或者那樣的關系。我們可以把節點之間的關系可以用傳統的家族關系來描述&#xff0c;可以把文檔樹當作一個家譜&#xff0c;那么節點與節點直接就會存在父子&#xff0c;兄弟&#xff0c;祖孫的關系了。 選擇器中的層級選擇器就是用來處理這種關…

文件 圖片 上傳 及少許正則校驗

文件 & 圖片 上傳 及少許正則校驗 <template><div style"padding: 20px"><Row><Col span"24"><div><CFlex type"flex" justify"space-between" align"midlle"><div class"…

bootstrap-table.js如何根據單元格數據不同顯示不同的字體的顏色

在bootstrap-table.js里面列屬性 formatter就是用來格式化單元格的&#xff0c;其默認值是undefined 類型是function&#xff0c;function(value, row, index), value&#xff1a;該cell本來的值&#xff0c;row&#xff1a;該行數據&#xff0c;index&#xff1a;該行序號&am…

SVN_06導入項目文檔

把這個項目的文檔遷入到SVN Server上的庫中 【1】首先右鍵點擊projectAdmin目錄&#xff0c;這時候的右鍵菜單例如以下圖看到的&#xff1a;選擇copy URL toCLipboard,就是復制統一資源定位符&#xff08;URL&#xff09;到剪貼板中 https://KJ-AP01.中國.corpnet:8443/svn/pro…

實現省市二級聯動效果

實現效果&#xff1a; 代碼&#xff1a; <template><div class"main_tableau"><div class"page_title">百城精算編輯</div><CFlex type"flex" justify"space-between"><div style"margin-top…

jquery操作select(取值,設置選中)

jquery操作select(增加&#xff0c;刪除&#xff0c;清空) http://huapengpeng1989412.blog.163.com/blog/static/58828754201342841940720/ jQuery獲取Select選擇的Text和Value: 123456789$("#select_id").change(function(){//code...}); //為Select添加事件&am…

手機驗證碼獲取

<el-form-item label"短信驗證碼" required><el-input v-model"ruleForm.verificationcode" placeholder"請添加驗證碼"><el-button v-if"isdisabled" slot"suffix" style"color:#409EFF;" type&…

關于RGB屏調試的一些知識(轉)

關于RGB屏調試的一些知識轉載于:https://www.cnblogs.com/LittleTiger/p/10983212.html

在bootstrap table中使用Tooltip

//偏好主題function preferenceFormatter(value, row, index) {var nameString "";if (value.length > 6) {nameString value.substring(0,6) ...;} else{nameString value;}return [<a href"#" data-toggle"tooltip" title value >…

實現值兩者之間添加 , 、 | 等字符

展示效果&#xff1a; <span v-for"(item, index) in projectData.bdOwnerList" :key"index"><span style"white-space: nowrap">{{ item.userName }}<spanv-if"projectData.bdOwnerList.length - 1 ! index"style&qu…

spring-cloud搭建

1、myApplicaion 啟動服務類上層必須有一層包 2、報錯 com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection refused: connect 或者com.netflix.discovery.shared.transport.TransportException: Cannot execute request on any known…

JS ===和==區別

這是一種隱式類型轉換 var a 12; var b 12; alert(a b);//先把兩邊的轉換成一樣的&#xff0c;再進行比較 。結果會返回true alert(a b);//不轉換兩邊類型&#xff0c;直接比較,結果返回false

單頁面輪播圖滾動

現在網上好多類似的效果&#xff0c;今天心情好&#xff0c;就私自模仿一個去&#xff0c;代碼如下。 單頁面網站 網站首頁公司簡介公司產品公司榮譽招聘英才聯系我們window.οnscrοllfunction(){ var scTopdocument.documentElement.scrollTop||document.body.scrollTop; va…

xBIM 基礎16 IFC的空間層次結構

系列目錄 【已更新最新開發文章&#xff0c;點擊查看詳細】 本篇介紹如何從文件中檢索空間結構。IFC中的空間結構表示層次結構的嵌套結構&#xff0c;表示項目&#xff0c;站點&#xff0c;建筑物&#xff0c;樓層和空間。如果您查看IFC文檔&#xff0c; 您會發現建筑物可以…

如何判斷兩個jq對象是同一個對象

如果說要判斷是否同一對象&#xff0c;當然是用 來判斷&#xff0c;但實際上兩個不同的 jQuery 對象可能是對同一個/組 DOM 對象的封裝&#xff0c;這個時候可以用 is 來判斷&#xff0c;比如 var a $(".editor"); var b $(".editor");console.log(a b…

狀態管理工具vuex的基本使用(vuebus的理解)

vuex的展示圖 1. vuex 的基本結構 const store new Vuex.Store({state: {} //相當于 vue結構中的 data getters: {}, // 相當于vue結構中的計算屬性使用actions: {}, // 相當于vue結構中的監聽屬性使用mutations: {},//相當于vue結構中的 methods 方法集合 &#xff08;其中方…

Memcache

前戲 Memcached是一個高性能的分布式內存對象緩存系統&#xff0c;用于動態Web應用以減輕數據庫負載。它通過在內存中緩存數據和對象減少讀取數據庫的次數&#xff0c;從而減小數據庫的壓力&#xff0c;提高動態&#xff0c;數據庫網站的速度。Memcached基于一個存儲 鍵/值對的…

解決Button自動刷新頁面的問題

一、問題 <button class"am-btn am-btn-default am-btn-xs am-text-secondary" data-id"99" data-type1><span class"am-icon-pencil-square-o"></span>修改</button>11 頁面上有這樣一個按鈕&#xff0c;每次點擊這個…

Django.1

Django官方網站&#xff1a;https://www.djangoproject.com/ 使用終端創建Django文件 創建工程 django-admin startproject XXX 創建應用 python manage.py startapp YYY 遷移系統指令&#xff1a; 首先生成遷移文件 python manage.py makemigrations 執行遷移文件 python ma…