Java 调用翻译软件实现英文文档翻译

前言:

因最近要进行OCP的考试准备。看着大堆英文文档确实有些疼痛。又因文档内容有点大,又需要逐一去翻译 又很费时费力。于是 百度了一番,找到一些 可以使用Java来调用百度翻译软件的API( 注:(官方标注)每月前200万字不要钱,49元/月) 。于是就自己手动的修改了一番。然后就使用。


Java调用百度API实现翻译


百度官方API 访问地址:http://api.fanyi.baidu.com/api/trans/product/apidoc

百度官方计费声明:

image

下面是Java调用百度API实现翻译的具体步骤:

一、在写代码之前先在在百度翻译平台中,申请APP_ID 

申请地址申请的详见 点击打开链接

申请之后,会得到APP_ID和SECURITY_KEY

二、java代码如下

       1:代码结构下图

image

       2:主要代码如下:

BaiduTranslateDemo

package spring;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 * 百度翻译引擎java示例代码
 */
public class BaiduTranslateDemo{

	private static final String UTF8 = "utf-8";

	//申请者开发者id,实际使用时请修改成开发者自己的appid
	private static final String appId = "自己注册一个appid";

	//申请成功后的证书token,实际使用时请修改成开发者自己的token
	private static final String token = "认证证书信息";

	private static final String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";

	//随机数,用于生成md5值,开发者使用时请激活下边第四行代码
	private static final Random random = new Random();

	public String translate(String q, String from, String to) throws Exception{
		//用于md5加密
		//int salt = random.nextInt(10000);
		//本演示使用指定的随机数为1435660288
		int salt = 1435660288;

		// 对appId+源文+随机数+token计算md5值
		StringBuilder md5String = new StringBuilder();
		md5String.append(appId).append(q).append(salt).append(token);
		String md5 = DigestUtils.md5Hex(md5String.toString());

		//使用Post方式,组装参数
		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("q", q));
		   nvps.add(new BasicNameValuePair("from", from));
		   nvps.add(new BasicNameValuePair("to", to));
		   nvps.add(new BasicNameValuePair("appid", appId));
		   nvps.add(new BasicNameValuePair("salt", String.valueOf(salt)));
		   nvps.add(new BasicNameValuePair("sign", md5));
		httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

		//创建httpclient链接,并执行
	    CloseableHttpClient httpclient = HttpClients.createDefault();
	    CloseableHttpResponse response = httpclient.execute(httpost);

	    //对于返回实体进行解析
		HttpEntity entity = response.getEntity();
		InputStream returnStream = entity.getContent();
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(returnStream, UTF8));
		StringBuilder result = new StringBuilder();
		String str = null;
		while ((str = reader.readLine()) != null) {
			result.append(str).append("\n");
		}

		//转化为json对象,注:Json解析的jar包可选其它
		JSONObject resultJson = new JSONObject(result.toString());

		//开发者自行处理错误,本示例失败返回为null
		try {
			String error_code = resultJson.getString("error_code");
			if (error_code != null) {
				System.out.println("出错代码:" + error_code);
				System.out.println("出错信息:" + resultJson.getString("error_msg"));
				return null;
			}
		} catch (Exception e) {}

		//获取返回翻译结果
		JSONArray array = (JSONArray) resultJson.get("trans_result");
		JSONObject dst = (JSONObject) array.get(0);
		String text = dst.getString("dst");
		text = URLDecoder.decode(text, UTF8);

		return text;
	}

	/**
	 * 实际抛出异常由开发者自己处理 中文翻译英文
	 * @param q
	 * @return
	 * @throws Exception
	 */
	public static  String translateZhToEn(String q) throws Exception{
		ApplicationContext container=new FileSystemXmlApplicationContext("src//spring//resource//baidu.xml");
		BaiduTranslateDemo baidu = (BaiduTranslateDemo)container.getBean("baidu");

		String result = null;
		try {
			result = baidu.translate(q, "zh", "en");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 实际抛出异常由开发者自己处理 英文翻译中文
	 * @param q
	 * @return
	 * @throws Exception
	 */
	public static  String translateEnToZh(String q) throws Exception{
		ApplicationContext container=new FileSystemXmlApplicationContext("src//spring//resource//baidu.xml");
		BaiduTranslateDemo baidu = (BaiduTranslateDemo)container.getBean("baidu");

		String result = null;
		try {
			result = baidu.translate(q, "en", "zh");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}

}


Main

package spring;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;

/**
 * 直接运行main方法即可输出翻译结果
 */
public class Main {

	public static void main(String[] args) throws Exception {
		// translateZhToEn();
		// translateEnToZh();
		translateTxtInfo();
	}

	/**
	 * 中文翻译为英文
	 */
	public static void translateZhToEn() {

		String source = "百度翻译引擎示例";
		String result;
		try {
			result = BaiduTranslateDemo.translateZhToEn(source);
			if (result == null) {
				System.out.println("翻译出错,参考百度错误代码和说明。");
				return;
			}
			System.out.println(source + "" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 英文翻译为中文
	 */
	public static void translateEnToZh() {

		String source = "CREATE GLOBAL TEMPORARY TABLE report_work_area";
		String result;
		try {
			result = BaiduTranslateDemo.translateEnToZh(source);
			if (result == null) {
				System.out.println("翻译出错,参考百度错误代码和说明。");
				return;
			}
			System.out.println(source + "" + result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取txt文件内容翻译为中文
	 */
	public static void translateTxtInfo() {
		String sorceFilePath = "E:\\txtfile\\052.txt";
		String resultFilePath = "E:\\\\txtfile\\\\test1.txt";
		// 构建指定文件
		File resultFile = new File(resultFilePath);
		FileReader fr = null;
		FileWriter fw = null;
		BufferedWriter bw = null;
		BufferedReader br = null;
		OutputStream out = null;
		String result;
		String line = "";
		try {
			// 根据文件创建文件的输入流
			fr = new FileReader(sorceFilePath);
			br = new BufferedReader(fr);
			fw = new FileWriter(new File(resultFilePath));
			// 写入中文字符时会出现乱码
			bw = new BufferedWriter(new BufferedWriter(
					new OutputStreamWriter(new FileOutputStream(new File(resultFilePath)), "UTF-8")));

			// 根据文件创建文件的输出流
			out = new FileOutputStream(resultFile);
			// 创建字节数组
			byte[] data = new byte[1024];
			StringBuffer resultBuffer=new StringBuffer();
			// 读取内容,放到字节数组里面
			while ((line = br.readLine()) != null) {
				String message = line.trim();
				// 英文翻译为中文 
				if(message.trim()!=null&& !message.trim().equals("")) {
					if(message.trim().indexOf("Answer")>-1) {
						resultBuffer.append(message+"\t\n");
					}else {
						result = BaiduTranslateDemo.translateEnToZh( message.trim());
						resultBuffer.append(message+"("+result+")"+"\t\n");
					}

				}

			}
			// 把内容转换成字节数组
			byte[] resultdata = resultBuffer.toString().getBytes();
			// 向文件写入内容
			out.write(resultdata);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				// 关闭输入流
				br.close();
				fr.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

}


        3:源码下载

image










Java 破解谷歌翻译 免费 api 调用


注 :本文来源于《Java 破解谷歌翻译 免费 api 调用

在公司大佬的指点下, 写了个破解谷歌翻译的工具类,能破解谷歌翻译, 思路如下:

1 获取 tkk 
2 根据 tkk,和 输入内容 获取 tk 
3 根据 word,tk ,组装 url 访问 谷歌翻译 api

调用如下:


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

输出:


  • 1

代码如下


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141

需要的js


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

jar 包下载:

http://download.csdn.net/download/qq_35704236/10156433

jar 包调用


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

jar 包输出


  • 1

写在最后:

但是 封ip 的速度太快了, 各位如果需要用于生产环境,必须加上ip 代理,如果实在不行。。。就换百度吧。。。虽然有字数限制。。

——————————————- 2018-5-16 ————————————————————-

应读者要求给出 Browser, 其实就是包装了下 http, 有需要的小伙伴可以直接下载上面的 jar包,如果积分不够 。。私聊楼主


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
想对作者说点什么

转载于:https://www.cnblogs.com/ios9/p/9651770.html

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值