Skip to content

Instantly share code, notes, and snippets.

@bvlion
Created September 12, 2017 14:35
Show Gist options
  • Save bvlion/ac4a3755857810fff808d44649615fe8 to your computer and use it in GitHub Desktop.
Save bvlion/ac4a3755857810fff808d44649615fe8 to your computer and use it in GitHub Desktop.
翻訳をJavaで実行してみるソース
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.stream.Collectors;
public class AzureService {
private static final String OCP_APIM_SUBSCRIPTION_KEY = "Ocp-Apim-Subscription-Key";
private static final String AUTH_API_URL = "https://api.cognitive.microsoft.com/sts/v1.0/issueToken";
private static final String SUBSCRIPTION_KEY = "ここに取得したキー";
private static final String TRANSLATOR_TEXT_API_URL = "https://api.microsofttranslator.com/v2/http.svc/Translate?";
private String getAccessToken() {
try {
URL url = new URL(AUTH_API_URL);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty(OCP_APIM_SUBSCRIPTION_KEY, SUBSCRIPTION_KEY);
connection.setDoOutput(true);
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.close();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), StandardCharsets.UTF_8.name()))) {
return reader.lines().collect(Collectors.joining());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String translate(String target) {
try {
String appId = URLEncoder.encode("Bearer " + getAccessToken(), StandardCharsets.UTF_8.name());
String text = URLEncoder.encode(target, StandardCharsets.UTF_8.name());
String accessUrl = TRANSLATOR_TEXT_API_URL
+ "appid="
+ appId
+ "&"
+ "text="
+ text
+ "&"
+ "from=en&to=ja";
URL url = new URL(accessUrl);
HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
connection.setRequestProperty("X-ClientTraceId", UUID.randomUUID().toString());
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream(), StandardCharsets.UTF_8.name()))) {
return reader.lines().collect(Collectors.joining()).replaceAll("<.+?>", "");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void main(String ... arg) {
System.out.println(new AzureService().translate("Partly sunny"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment