Java: Using SSL with the Microsoft Translator API

Here is the working code with HTTPS.

private static final String httpsTranslateURLTemplate = "https://api.microsofttranslator.com/V2/Ajax.svc/Translate?from=%1s&to=%2s&appid=%3s&text=%4s";
     
public static void main(String[] args) {
            AdmAccessToken accessToken = AdmAccessToken.getAccessToken("ClientID", "ClientSecret");
           
            String translatedText = Translate(accessToken.access_token, "en", "fr", "today is sunday");
            System.out.printf("Translated Text: "+ translatedText);
}


private static String Translate(String accessToken, String from, String to, String text) {
            try {
                  String accessTokenToSend = UrlEncoded.encodeString("Bearer " + accessToken, StandardCharsets.UTF_8);
                  String textToSend = UrlEncoded.encodeString(text, StandardCharsets.UTF_8);
                  URL translateUrl = new URL(String.format(httpsTranslateURLTemplate, from, to, accessTokenToSend, textToSend));
                  HttpsURLConnection connection = (HttpsURLConnection) translateUrl.openConnection();
                  connection.getResponseCode();
                  try (BufferedReader reader = new BufferedReader(new InputStreamReader(translateUrl.openStream(), StandardCharsets.UTF_8))) {
                        StringBuffer res = new StringBuffer();
                        String line;
                        while ((line = reader.readLine()) != null) {
                              res.append(line);
                        }
                        return res.toString();
                  }

            } catch (Exception e) {
                  e.printStackTrace();
            }
            return null;
      }

Feedback and Knowledge Base