More Related Content
Similar to Microsoft translator text apiで自動翻訳 (20)
Microsoft translator text apiで自動翻訳
- 28. import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class Token {
public static String get(String キー管理のキー1) throws Exception {
HttpPost request = new HttpPost("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");
request.setHeader("Ocp-Apim-Subscription-Key", キー管理のキー1);
return EntityUtils.toString(HttpClients.createDefault().execute(request).getEntity());
}
}
ステップ1
Authentication Tokenを取得
https://github.com/grachro/MicrosoftTranslatorTextApi-JavaSampleサンプル
- 29. import org.apache.commons.codec.net.URLCodec;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
public class Translater {
public static String translate(String accessToken, String fromLocale, String toLocale, String text) throws Exception {
String encoded = new URLCodec().encode(text, "UTF-8");
String theRequestURI = "https://api.microsofttranslator.com/v2/Ajax.svc/Translate";
String url = String.format("%s?from=%s&to=%s&text=%s", theRequestURI, fromLocale, toLocale, encoded);
HttpGet request = new HttpGet(url);
request.setHeader("Authorization", "Bearer " + accessToken);
String resultJson = EntityUtils.toString(HttpClients.createDefault().execute(request).getEntity());
return new Gson().fromJson(resultJson, String.class);
}
}
ステップ2 translatorAPIで翻訳します。
https://github.com/grachroサンプル
token
翻訳元
Locale 翻訳先
Locale
文書
- 30. String token = Token.get(キー管理のキー1);
String text = "クラウド";//<-日本語
String fromLang = "ja-JP";
String simplifiedChinese = Translater.translate(token, fromLang, "zh-CN", text);
String traditionalChinese = Translater.translate(token, fromLang, "zh-HK", text);
String english = Translater.translate(token, fromLang, "en-US", text);
System.out.printlnsimplifiedChinese); //云计算 <-簡体字
System.out.println(traditionalChinese); //雲計算 <-繁体字
System.out.println(english); //Cloud <-英語
日本語から簡体字・繁体字・英語に翻訳する場合