如何使用
1、申请百度通用翻译API接口能力或其他你觉得更高效的接口能力
2、下载json.jar并放在app/bin目录下
3、复制代码
- app\src\test\java\com.yourpackage\ExampleUnitTest.java
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
private void genRes(String...targets){
final File fResZhPath = new File( "src\\main\\res\\values\\strings.xml");
final String resPath = "src\\main\\res\\";
if(targets==null||targets.length==0){
System.out.println("无效的目标语言转换!");
return;
}
if(!fResZhPath.exists()){
System.out.println("中文资源文件不存在!");
return;
}
List<String> lstGen = new ArrayList<>(Arrays.asList(targets));
for(String str:lstGen){
System.out.println("开始转换:"+str);
File fRes = new File(String.format("%svalues-%s\\strings.xml",resPath,str));
if(!fRes.exists()&&!fRes.getParentFile().exists())
fRes.getParentFile().mkdirs();
else
fRes.delete();
try {
fRes.createNewFile();
} catch (Exception e) {
System.out.println(fRes.getAbsolutePath()+"创建失败!\n检查磁盘空间或以管理员权限运行Android Studio!");
e.printStackTrace();
continue;
}
FileReader fin = null;
BufferedReader bf = null;
FileOutputStream fout = null;
try {
fin = new FileReader(fResZhPath);
bf = new BufferedReader(fin);
fout = new FileOutputStream(fRes);
String strLine,strProc="";
// 按行读取字符串
while ((strLine = bf.readLine()) != null) {
strProc= strProc.length()==0?strLine:(strProc+"\n"+strLine);
for(int i=0,ni=strProc.length();i<ni;++i){
if(strProc.charAt(i)=='<'){
if(i==0){
while(i<ni&&strProc.charAt(i)!='>') ++i;
if(i<ni){
String strTmp = strProc.substring(0,i+1);
fout.write(strTmp.getBytes());
if(strTmp.contains("</")||strTmp.contains("<resources>")){
fout.write("\n".getBytes());
}
strProc=strProc.substring(i+1);
i=-1;
ni=strProc.length();
}
}
else{
String strTrans = strProc.substring(0,i);//需要从中文翻译的字符串
if(strTrans.trim().length()==0){//空串不处理
fout.write(strTrans.getBytes());
}
else{//处理非空 你可以接其他平台的api自己处理 这里使用的百度通用翻译http://api.fanyi.baidu.com/product/11
String strTransResult = BaiduTransApi.getTransResult(strTrans,"zh",str);
System.out.println(str+":"+strTrans+"->"+strTransResult);
JSONObject jsonObject = new JSONObject(strTransResult);
JSONArray jsonResult = jsonObject.getJSONArray("trans_result");
JSONObject jsonData = jsonResult.getJSONObject(0);
String strWrite = jsonData.getString("dst");
int idx = 0;
while((idx=strWrite.indexOf("'",idx))>-1){
strWrite = strWrite.substring(0,idx)+"\\"+strWrite.substring(idx);
idx+=2;
}
fout.write(strWrite.getBytes());
Thread.sleep(1000);//标准版QPS=1 需要等待
//Thread.sleep(100);// 高级版QPS=10 可以设置100但有字数限制
//Thread.sleep(10);// 尊享版QPS=100 可以设置10
//我不是来打广告的 只是告诉你设置多少合适
}
strProc = strProc.substring(i);
i=-1;
ni=strProc.length();
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
finally {
try { fout.close(); } catch (Exception e) { }
try { bf.close(); } catch (Exception e) { }
try { fin.close(); } catch (Exception e) { }
}
System.out.println("完成转换:"+str);
}
System.out.println("--------------------------------------------------------------------------");
System.out.println("--------------------------------------------------------------------------");
System.out.println("全部任务已转换完成!");
System.out.println("--------------------------------------------------------------------------");
System.out.println("--------------------------------------------------------------------------");
}
@Test
public void addition_isCorrect(){
genRes("en");
}
}
- app\src\test\java\com.yourpackage\BaiduTransApi.java
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.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class BaiduTransApi {
//region API
private final static String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
private final static String appid = "你自己的appid";
private final static String securityKey = "你自己的密钥";
public static String getTransResult(final String query, final String from,final String to) {
return HttpGet(TRANS_API_HOST, new HashMap<String, String>(){{
put("q", query);
put("from", from);
put("to", to);
put("appid", appid);
// 随机数
String salt = String.valueOf(System.currentTimeMillis());
put("salt", salt);
// 签名
String src = appid + query + salt + securityKey; // 加密前的原文
put("sign", md5(src));
}});
}
//endregion
//region Http Get
protected static final int SOCKET_TIMEOUT = 10000; // 10S
protected static final String GET = "GET";
public static String HttpGet(String host, Map<String, String> params) {
try {
// 设置SSLContext
SSLContext 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 (Exception 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) { // 过滤空的key
continue;
}
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() {
@Override
public X509Certificate[] getAcceptedIssuers() {
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
};
//endregion
//region 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 (Exception e) {
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);
}
//endregion
}
4、在BaiduTransApi.java配置好你自己的appid和秘钥
5、在ExampleUnitTest.java注解的测试入口调用genRes(“en”);参数可以是其他百度接口支持的语言,且个数是任意的。
注意:转义字符需要自己处理
注意:你的格式化可能被百度吃掉,语种只测试过英文,其他可能需要修改文件夹名称。