Java 调用 有道翻译API


利用有道API进行翻译
   
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;


public class YoudaoTranslate {

 
 private String url = "http://fanyi.youdao.com/openapi.do";

 
 private String keyfrom = "";
 private String key = "";

 
 private String doctype = "xml";

 
 private String sendGet(String str) {

  // 编码成UTF-8
  try {
   str =URLEncoder.encode(str, "utf-8");
  } catch(UnsupportedEncodingException e) {
   e.printStackTrace();
  }

  StringBuffer buf = newStringBuffer();
  buf.append("keyfrom=");
  buf.append(keyfrom);
  buf.append("&key=");
  buf.append(key);
  buf.append("&type=data&doctype=");
  buf.append(doctype);
  buf.append("&version=1.1&q=");
  buf.append(str);

  String param =buf.toString();

  String result = "";
  BufferedReader in = null;
  try {
   StringurlName = url + "?" + param;
   URL realUrl =new URL(urlName);

   //打开和URL之间的连接
   URLConnectionconn = realUrl.openConnection();

   //设置通用的请求属性
   //conn.setRequestProperty("accept", "*
 public String getYouDaoValue(String str) {
  String result = null;

  // 发送GET请求翻译
  result = sendGet(str);

  // 处理XML中的值
  int re1 =result.indexOf("<errorCode>");
  int re2 =result.indexOf("</errorCode>");
  String in =result.substring(re1 + 11, re2);
  System.out.println("===========翻译是否成功============"+ in);

  if (in.equals("0")) {
   System.out.println("翻译正常");

   re1 =result.indexOf("<paragraph><![CDATA[");
   re2 =result.indexOf("]]></paragraph>");
   in =result.substring(re1 + 20, re2);
   System.out.println("==========有道翻译================"+ in);

   re1 =result.indexOf("<ex><![CDATA[");
   re2 =result.indexOf("]]></ex>");
   in =result.substring(re1 + 13, re2);
   System.out.println("==========有道词典-网络释义================"+ in);

  } else if (in.equals("20")){
   System.out.println("要翻译的文本过长");
   return"要翻译的文本过长";
  } else if (in.equals("30")){
   System.out.println("无法进行有效的翻译");
   return"无法进行有效的翻译";
  } else if (in.equals("40")){
   System.out.println("不支持的语言类型");
   return"不支持的语言类型";
  } else if (in.equals("50")){
   System.out.println("无效的key");
   return"无效的key";
  }

  return result;
 }

 public static void main(String[] args) {

  String str = "The weather isgood today";
 

 YoudaoTranslate test = newYoudaoTranslate();
  String temp =test.getYouDaoValue(str);
  System.out.println(temp);
 }

}


原文地址:http://blog.sina.com.cn/s/blog_4d641b4f010120vj.html

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
调用有道翻译API需要以下步骤: 1. 注册有道智云开发者账号并创建应用,获取应用ID和应用密钥。 2. 使用HTTP POST方法向API发送请求,请求URL为:http://openapi.youdao.com/api 。 3. 在请求中添加必要的参数,包括应用ID、应用密钥、待翻译文本等。 4. 发送请求并获取响应。 5. 解析响应,获取翻译结果。 下面是一个使用C++调用有道翻译API的示例代码: ```c++ #include <iostream> #include <curl/curl.h> #include <cstring> #include <sstream> #include <json/json.h> using namespace std; // 应用ID和应用密钥 const string APP_ID = "your_app_id"; const string APP_KEY = "your_app_key"; // 发送HTTP POST请求 size_t post_callback(void* ptr, size_t size, size_t nmemb, void* stream) { string* response = (string*)stream; response->append((char*)ptr, size * nmemb); return size * nmemb; } // 调用有道翻译API翻译文本 string translate(string text) { // 初始化CURL CURL* curl = curl_easy_init(); // 初始化请求参数 struct curl_slist* headers = NULL; headers = curl_slist_append(headers, "Content-Type:application/x-www-form-urlencoded"); stringstream ss; ss << "appKey=" << APP_ID << "&"; ss << "q=" << curl_easy_escape(curl, text.c_str(), 0) << "&"; ss << "salt=1&"; ss << "signType=v3&"; ss << "version=2.1&"; string sign_str = APP_ID + text + "1" + APP_KEY; unsigned char md[16]; CURLcode res = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false); res = curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, false); res = curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); res = curl_easy_setopt(curl, CURLOPT_URL, "http://openapi.youdao.com/api"); res = curl_easy_setopt(curl, CURLOPT_POSTFIELDS, ss.str().c_str()); res = curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, post_callback); // 发送请求并获取响应 string response; res = curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response); res = curl_easy_perform(curl); // 解析JSON响应 Json::CharReaderBuilder builder; Json::CharReader* reader = builder.newCharReader(); Json::Value value; JSONCPP_STRING errs; reader->parse(response.c_str(), response.c_str() + response.size(), &value, &errs); delete reader; string result = value["translation"][0].asString(); // 释放资源 curl_easy_cleanup(curl); curl_slist_free_all(headers); return result; } int main() { string text = "hello world"; string translation = translate(text); cout << text << " -> " << translation << endl; return 0; } ``` 需要注意的是,该示例代码中使用了CURL库和JSON库,需要在编译时链接这两个库。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值