I have tried the Microsoft Translator text API in Java. p>
I couldn't find the Java sample source unexpectedly, so I will publish it as a reference.
You can use it immediately if you change the key, tokenUrl, and transUrl according to your environment.
By the way, you need to use your own key, which is as follows.
tokenUrl (Token API for authentication-URL)
https://api.cognitive.microsoft.com/sts/v1.0/issueToken
transUrl (API for translation-URL)
https://api.microsofttranslator.com/V2/http.svc/TranslateArray
@Component
public class TranslatorAPI {
@Value("${translation.subscriptionKey}")
private String key;
@Value("${translation.tokenApi.url}")
private String tokenUrl;
@Value("${translation.transApi.url}")
private String transUrl;
/**
*Translate the target character string into English.
* @param words Target character
* @return translation result
*/
public String[] translator(String... words) {
return translatorPOSTToEN(words);
}
/**
*Get a token.
*/
private String tokenPOST() {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost postMethod = new HttpPost(tokenUrl);
// Header
postMethod.setHeader("Content-Type", "application/json");
postMethod.setHeader("Accept", "application/jwt");
postMethod.setHeader("Ocp-Apim-Subscription-Key", key);
try (CloseableHttpResponse response = httpClient.execute(postMethod)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
return EntityUtils.toString(entity, StandardCharsets.UTF_8);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
*Post to the translation API.
*/
private String[] translatorPOSTToEN(String... words) {
List<String> rtnWords = new ArrayList<String>();
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost postMethod = new HttpPost(transUrl);
// header
//Get authentication token
String token = tokenPOST();
String authKey = "Bearer " + token;
postMethod.setHeader("Content-Type", "application/xml");
postMethod.setHeader("Authorization", authKey);
//Translated word
StringBuilder transWords = new StringBuilder();
for (String word : words) {
transWords.append("<string xmlns='http://schemas.microsoft.com/2003/10/Serialization/Arrays'>");
transWords.append(word);
transWords.append("</string>");
}
StringBuilder requestSB = new StringBuilder();
requestSB.append("<TranslateArrayRequest>");
requestSB.append("<AppId />");
requestSB.append("<Texts>");
requestSB.append(transWords.toString());
requestSB.append("</Texts>");
//Specify the language to be translated
requestSB.append("<To>en</To>");
requestSB.append("</TranslateArrayRequest>");
postMethod.setEntity(new StringEntity(requestSB.toString(),
StandardCharsets.UTF_8));
try (CloseableHttpResponse response = httpClient.execute(postMethod)) {
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
String res = EntityUtils.toString(entity, StandardCharsets.UTF_8);
InputSource inputSource = new InputSource(new StringReader(res));
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = factory.newDocumentBuilder();
Document document = documentBuilder.parse(inputSource);
//Sort the character string sentence to be translated
Element root = document.getDocumentElement();
NodeList rootChildren = root.getChildNodes();
for (int i = 0; i < rootChildren.getLength(); i++) {
Node node = rootChildren.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
String val = element.getElementsByTagName("TranslatedText").item(0).getFirstChild().getNodeValue();
rtnWords.add(val);
}
}
}
}
} catch (ParserConfigurationException | SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return rtnWords.toArray(new String[rtnWords.size()]);
}
}
//sample
String[] words = tranApi.translator("this is a pen", "Apples are delicious");
for (String word : words) {
System.out.println(word);
}
This is a pen.
Apple delicious
Recommended Posts