java 调用百度翻译接口

md5加密类  百度翻译Demo有 

package com.jddz.meta.util;

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 ljj
 *
 */
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) throws UnsupportedEncodingException {
        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;
        }
    }

    /**
     * 获取文件的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);

    }

}

 

Service层

package com.jddz.meta.cp500.common.service;

import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.jddz.meta.cp500.common.exception.StatisResult;
import com.jddz.meta.cp500.common.exception.StatisResultUtil;
import com.jddz.meta.util.MD5;
import com.jddz.meta.util.http.HttpClientService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 *
 * @author ljj
 *
 */

@Service
public class TransApiService {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
	@Value("#{sync['bd.id']}")//根据配置文件传入id
    private String appid;
	@Value("#{sync['bd.key']}")//根据配置文件传入key
    private String securityKey;
    
    
    @Autowired
    private HttpClientService httpClientService;

    
    public TransApiService() {
		super();
	}

    public String getTransResult(String query, String from, String to) throws Exception {
    	
        Map<String, String> params = buildParams(query, from, to,appid,securityKey);
         
        
        return httpClientService.doGet(TRANS_API_HOST, params);
     	
    }
    
    /**
     *
     * @param transResult
     * @return
     */
    //只获取翻译后的dst 方法
   public StatisResult JsonToSplit(String transResult) {
    	JSONObject jsonObject = JSONObject.fromObject(transResult);
		Object msg = jsonObject.get("trans_result");
		JSONArray array = JSONArray.fromObject(msg);
		String res="";
		for(int i=0; i<array.size();i++) {
			JSONObject ob  = (JSONObject) array.get(i);
			 res=ob.getString("dst");
			
		}
		return StatisResultUtil.success(res);
    	
    }
    
  
	  /**
	 * 百度翻译接口
	 * @param query   请求翻译query
	 * @param from     翻译源语言()
	 * @param to		译文语言
	 * @param appid   APP ID
	 * @param securityKey  密钥 
	 * @return
	 * @throws Exception
	 */
    private Map<String, String> buildParams(String query, String from, String to,String appid,String securityKey) throws Exception  {
        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;
    }
     

}

controller   

406 报错   produces(与返回值不一致 报406错)     

charset  produces 可以无需写     

package com.jddz.meta.cp500.common.web;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.jddz.meta.cp500.common.service.TransApiService;
import com.jddz.meta.cp500.common.exception.StatisResult;
import com.jddz.meta.cp500.common.exception.StatisResultUtil;
/**
 * 
 * @author ljj
 *
 */

@Controller
@RequestMapping("/BaiduAPI")
public class FanyiAPIController {

	@Autowired 
	private TransApiService transApiService;
	
	/**
	 * 
	 * @param query
	 * @param from
	 * @param to
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="getFanyi",produces="application/json; charset=UTF-8")
	produces(与返回值不一致 报406错) charset 可以无需写     
	@ResponseBody
	public  Object getFanyi(@RequestParam (value="query") String query,
							@RequestParam(value="from") String from,
							@RequestParam(value="to") String to)    {

		String transResult="";	
		try {
			 query =new String(query.getBytes("iso8859-1"),"utf-8");
			 transResult = transApiService.getTransResult(query, "auto", "zh");	 
			StatisResult jo = transApiService.JsonToSplit(transResult);
			System.out.println(jo);  
             //com.jddz.meta.cp500.common.exception.StatisResult@6077ab06
			return  StatisResultUtil.success(jo);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	  return transResult;

		
			
}

    }
	 
	



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值