Translate using Microsoft Translator Text API in Java (Japanese → English)

I have tried the Microsoft Translator text API in Java.

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

Source


@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()]);
    }

}

Verification

call

        //sample
        String[] words = tranApi.translator("this is a pen", "Apples are delicious");
        for (String word : words) {
            System.out.println(word);
        }

Output result

This is a pen.
Apple delicious

Recommended Posts

Translate using Microsoft Translator Text API in Java (Japanese → English)
Translator using Microsoft Translator Text API on Android ~ Implementation ~
I tried using Elasticsearch API in Java
Try using the Stream API in Java
Try using JSON format API in Java
ChatWork4j for using the ChatWork API in Java
[Java] API creation using Jerjey (Jax-rs) in eclipse
Try using GCP's Cloud Vision API in Java
Try using the COTOHA API parsing in Java
Zabbix API in Java
Try using RocksDB in Java
Java Stream API in 5 minutes
Elasticsearch Operation via REST API using Apache HttpClient in Java
Tips for using Salesforce SOAP and Bulk API in Java
NLP4J [001a] Morphological analysis in Java (using Yahoo! Developer Network Japanese morphological analysis)
Easily read text files in Java (Java 11 & Java 7)
Export issues using JIRA's Java API
Encrypt using RSA cryptography in Java
Generate CloudStack API URL in Java
Hit Zaim's API (OAuth 1.0) in Java
Parsing the COTOHA API in Java
HTTPS connection using tls1.2 in Java 6
I tried using JWT in Java
JPA (Java Persistence API) in Eclipse
NLP4J [002] Try parsing Japanese using Yahoo! Developer Network Japanese Parsing Analysis (V1) in Java
Implement API Gateway Lambda Authorizer in Java Lambda
Data processing using stream API from Java 8
Studying Java 8 (date API in java.time package)
Call the Windows Notification API in Java
Map without using an array in java
Using JavaScript from Java in Rhino 2021 version
ERRORCODE = -4471 occurs in Java application using Db2.
Read Felica using RC-S380 (PaSoRi) in Java
Try adding text to an image in Scala using the Java standard library
NLP4J [004] Try text analysis using natural language processing and parsing statistical processing in Java
NLP4J [003] Try text analysis using natural language processing and part-speech statistical processing in Java