初体验java版(第2篇)

2017年08月30日 08:37 | 3949次浏览 作者原创 版权保护

上一节详细介绍了百度翻译开放平台的开发文档,其实百度开放平台的API已经说得很详细了,接下来让我们初步体验百度翻译的魅力吧。

第一步:登录百度翻译开放平台,接入文档界面-下载百度翻译java开发包


第二步:解压压缩包,然后打开Eclipse,引入工程项目,工程项目结构如下

1,我们只要熟悉上图中两个红色箭头的类即可,BaiduTranslateDemo.java类中主要是配置一些核心参数,例如申请中开发者id,申请成功后的证书Token等

2,Main类中主要是调用百度翻译源码包中的方法,给开发者提供一个体验百度翻译开发的执行窗口。

第三、配置核心参数

1),登录百度翻译开放平台,然后管理控制平台-开发者信息,如下图

上图红色圈部分便是开发者重要的核心参数,然后我们打开BaiduTranslateDemo.java,把里面的final变量更换成我们自己的即可。

第四,初步体验百度翻译开发的魅力

把压缩包引入工程项目后,BaiduTranslateDemo.java里面的参数配置替换,然后打开Main类,执行main方法,效果如下

执行后,中文"百度翻译引擎示例"已经翻译成了英文。

第五、java示例代码

BaiduTranslateDemo.java

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示例代码
 * www.vxzsk.com V型知识库
 */
public class BaiduTranslateDemo{
	
	private static final String UTF8 = "utf-8";
	
	//申请者开发者id,实际使用时请修改成开发者自己的appid
	private static final String appId = "2015063000000001";

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

	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;
	}
	
	//实际抛出异常由开发者自己处理
	public static  String translateToEn(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;
	}
}

Main.java

package spring;

/**
 * 直接运行main方法即可输出翻译结果
 * www.vxzsk.com V型知识库
 */
public class Main {
	
	public static void main(String[] args) throws Exception {
		String source = "百度翻译引擎示例";
		String result = BaiduTranslateDemo.translateToEn(source);
		if(result == null){
			System.out.println("翻译出错,参考百度错误代码和说明。");
			return;
		}
		System.out.println(source + ":" + result);
	}
}



小说《我是全球混乱的源头》
此文章本站原创,地址 https://www.vxzsk.com/153.html   转载请注明出处!谢谢!

感觉本站内容不错,读后有收获?小额赞助,鼓励网站分享出更好的教程